标签:des android http color io os ar 使用 java
View是所有控件的一个基类,无论是布局(Layout),还是控件(Widget)都是继承自View类。只不过layout是一个特殊的view,它里面创建一个view的数组可以包含其他的view而已。
这一篇文章把所有的layout和widget都统称为view,那么android是如何创建一个view的呢?
一。在代码中直接new出来。
比如说你要创建一个TextView的实例,那么你可以这样写:
- TextView text = new TextView(c);
二。把控件写在xml文件中然后通过LayoutInflater初始化一个view。
注意:下面的内容不是顺序的看的而是交替的看的。否则可能弄迷糊。
可以通过
- LayoutInflater inflater = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
- View view = inflater.inflate(R.layout.resourceid, null);
这样也得到了一个view的实例,让我们一步一步来看,这个view是怎么new出来的。
看类android.view.LayoutInflater
- public View inflate(int resource, ViewGroup root) {
- return inflate(resource, root, root != null);
- }
-
- public View inflate(int resource, ViewGroup root, boolean attachToRoot) {
-
- XmlResourceParser parser = getContext().getResources().getLayout(resource);
- try {
- return inflate(parser, root, attachToRoot);
- } finally {
- parser.close();
- }
- }
-
-
- public View inflate(XmlPullParser parser, ViewGroup root, boolean attachToRoot) {
- synchronized (mConstructorArgs) {
-
- final AttributeSet attrs = Xml.asAttributeSet(parser);
- mConstructorArgs[0] = mContext;
- View result = root;
-
- try {
-
- int type;
- while ((type = parser.next()) != XmlPullParser.START_TAG &&
- type != XmlPullParser.END_DOCUMENT) {
-
- }
-
- if (type != XmlPullParser.START_TAG) {
- throw new InflateException(parser.getPositionDescription()
- + ": No start tag found!");
- }
-
- final String name = parser.getName();
-
-
-
- if (TAG_MERGE.equals(name)) {
- if (root == null || !attachToRoot) {
- throw new InflateException("<merge /> can be used only with a valid "
- + "ViewGroup root and attachToRoot=true");
- }
-
- rInflate(parser, root, attrs);
- } else {
-
- View temp = createViewFromTag(name, attrs);
-
- ViewGroup.LayoutParams params = null;
-
- if (root != null) {
-
- params = root.generateLayoutParams(attrs);
- if (!attachToRoot) {
-
-
- temp.setLayoutParams(params);
- }
- }
-
-
-
- rInflate(parser, temp, attrs);
-
-
-
- if (root != null && attachToRoot) {
- root.addView(temp, params);
- }
-
-
-
- if (root == null || !attachToRoot) {
- result = temp;
- }
- }
-
- } catch (XmlPullParserException e) {
- InflateException ex = new InflateException(e.getMessage());
- ex.initCause(e);
- throw ex;
- } catch (IOException e) {
- InflateException ex = new InflateException(
- parser.getPositionDescription()
- + ": " + e.getMessage());
- ex.initCause(e);
- throw ex;
- }
-
- return result;
- }
- }
-
-
- private void rInflate(XmlPullParser parser, View parent, final AttributeSet attrs)
- throws XmlPullParserException, IOException {
-
- final int depth = parser.getDepth();
- int type;
-
- while (((type = parser.next()) != XmlPullParser.END_TAG ||
- parser.getDepth() > depth) && type != XmlPullParser.END_DOCUMENT) {
-
- if (type != XmlPullParser.START_TAG) {
- continue;
- }
-
- final String name = parser.getName();
-
- if (TAG_REQUEST_FOCUS.equals(name)) {
- parseRequestFocus(parser, parent);
- } else if (TAG_INCLUDE.equals(name)) {
- if (parser.getDepth() == 0) {
- throw new InflateException("<include /> cannot be the root element");
- }
- parseInclude(parser, parent, attrs);
- } else if (TAG_MERGE.equals(name)) {
- throw new InflateException("<merge /> must be the root element");
- } else {
- final View view = createViewFromTag(name, attrs);
- final ViewGroup viewGroup = (ViewGroup) parent;
- final ViewGroup.LayoutParams params = viewGroup.generateLayoutParams(attrs);
- rInflate(parser, view, attrs);
- viewGroup.addView(view, params);
- }
- }
-
- parent.onFinishInflate();
- }
-
-
- View createViewFromTag(String name, AttributeSet attrs) {
- if (name.equals("view")) {
- name = attrs.getAttributeValue(null, "class");
- }
-
- if (DEBUG) System.out.println("******** Creating view: " + name);
-
- try {
- View view = (mFactory == null) ? null : mFactory.onCreateView(name,
- mContext, attrs);
-
- if (view == null) {
- if (-1 == name.indexOf(‘.‘)) {
- view = onCreateView(name, attrs);
- } else {
- view = createView(name, null, attrs);
- }
- }
-
- if (DEBUG) System.out.println("Created view is: " + view);
- return view;
-
- } catch (InflateException e) {
- throw e;
-
- } catch (ClassNotFoundException e) {
- InflateException ie = new InflateException(attrs.getPositionDescription()
- + ": Error inflating class " + name);
- ie.initCause(e);
- throw ie;
-
- } catch (Exception e) {
- InflateException ie = new InflateException(attrs.getPositionDescription()
- + ": Error inflating class " + name);
- ie.initCause(e);
- throw ie;
- }
- }
-
- public final View createView(String name, String prefix, AttributeSet attrs)
- throws ClassNotFoundException, InflateException {
- Constructor constructor = sConstructorMap.get(name);
- Class clazz = null;
-
- try {
- if (constructor == null) {
-
- clazz = mContext.getClassLoader().loadClass(
- prefix != null ? (prefix + name) : name);
-
- if (mFilter != null && clazz != null) {
- boolean allowed = mFilter.onLoadClass(clazz);
- if (!allowed) {
- failNotAllowed(name, prefix, attrs);
- }
- }
-
- constructor = clazz.getConstructor(mConstructorSignature);
- sConstructorMap.put(name, constructor);
- } else {
-
- if (mFilter != null) {
-
- Boolean allowedState = mFilterMap.get(name);
- if (allowedState == null) {
-
- clazz = mContext.getClassLoader().loadClass(
- prefix != null ? (prefix + name) : name);
-
- boolean allowed = clazz != null && mFilter.onLoadClass(clazz);
- mFilterMap.put(name, allowed);
- if (!allowed) {
- failNotAllowed(name, prefix, attrs);
- }
- } else if (allowedState.equals(Boolean.FALSE)) {
- failNotAllowed(name, prefix, attrs);
- }
- }
- }
-
- Object[] args = mConstructorArgs;
- args[1] = attrs;
- return (View) constructor.newInstance(args);
-
- } catch (NoSuchMethodException e) {
- InflateException ie = new InflateException(attrs.getPositionDescription()
- + ": Error inflating class "
- + (prefix != null ? (prefix + name) : name));
- ie.initCause(e);
- throw ie;
-
- } catch (ClassNotFoundException e) {
-
- throw e;
- } catch (Exception e) {
- InflateException ie = new InflateException(attrs.getPositionDescription()
- + ": Error inflating class "
- + (clazz == null ? "<unknown>" : clazz.getName()));
- ie.initCause(e);
- throw ie;
- }
- }
在类android.content.res.Resources类中获取XmlResourceParser对象;
- public XmlResourceParser getLayout(int id) throws NotFoundException {
- return loadXmlResourceParser(id, "layout");
- }
-
- ackage*/ XmlResourceParser loadXmlResourceParser(int id, String type)
- throws NotFoundException {
- synchronized (mTmpValue) {
- TypedValue value = mTmpValue;
- getValue(id, value, true);
- if (value.type == TypedValue.TYPE_STRING) {
- return loadXmlResourceParser(value.string.toString(), id,
- value.assetCookie, type);
- }
- throw new NotFoundException(
- "Resource ID #0x" + Integer.toHexString(id) + " type #0x"
- + Integer.toHexString(value.type) + " is not valid");
- }
- }
-
-
- public void getValue(int id, TypedValue outValue, boolean resolveRefs)
- throws NotFoundException {
- boolean found = mAssets.getResourceValue(id, outValue, resolveRefs);
- if (found) {
- return;
- }
- throw new NotFoundException("Resource ID #0x"
- + Integer.toHexString(id));
- }
-
-
- int assetCookie, String type) throws NotFoundException {
- if (id != 0) {
- try {
-
- synchronized (mCachedXmlBlockIds) {
-
- final int num = mCachedXmlBlockIds.length;
- for (int i=0; i<num; i++) {
- if (mCachedXmlBlockIds[i] == id) {
-
-
- return mCachedXmlBlocks[i].newParser();
- }
- }
-
-
-
- XmlBlock block = mAssets.openXmlBlockAsset(
- assetCookie, file);
-
-
-
-
- if (block != null) {
- int pos = mLastCachedXmlBlockIndex+1;
- if (pos >= num) pos = 0;
- mLastCachedXmlBlockIndex = pos;
- XmlBlock oldBlock = mCachedXmlBlocks[pos];
- if (oldBlock != null) {
- oldBlock.close();
- }
- mCachedXmlBlockIds[pos] = id;
- mCachedXmlBlocks[pos] = block;
-
- return block.newParser();
- }
- }
- } catch (Exception e) {
- NotFoundException rnf = new NotFoundException(
- "File " + file + " from xml type " + type + " resource ID #0x"
- + Integer.toHexString(id));
- rnf.initCause(e);
- throw rnf;
- }
- }
-
- throw new NotFoundException(
- "File " + file + " from xml type " + type + " resource ID #0x"
- + Integer.toHexString(id));
- }
android.content.res.AssetManager类
-
- TypedValue outValue,
- boolean resolveRefs)
- {
- int block = loadResourceValue(ident, outValue, resolveRefs);
- if (block >= 0) {
- if (outValue.type != TypedValue.TYPE_STRING) {
- return true;
- }
-
- outValue.string = mStringBlocks[block].get(outValue.data);
- return true;
- }
- return false;
- }
-
-
- private native final int loadResourceValue(int ident, TypedValue outValue,
- boolean resolve);
-
-
-
-
-
- throws IOException {
- synchronized (this) {
- if (!mOpen) {
- throw new RuntimeException("Assetmanager has been closed");
- }
- int xmlBlock = openXmlAssetNative(cookie, fileName);
- if (xmlBlock != 0) {
-
- XmlBlock res = new XmlBlock(this, xmlBlock);
- incRefsLocked(res.hashCode());
- return res;
- }
- }
- throw new FileNotFoundException("Asset XML file: " + fileName);
- }
三 。通过view.findViewById(resourceid)获得一个view的实例
android.View.View类中
-
- public final View findViewById(int id) {
- if (id < 0) {
- return null;
- }
- return findViewTraversal(id);
- }
-
- protected View findViewTraversal(int id) {
- if (id == mID) {
- return this;
- }
- return null;
- }
android.View.ViewGroup类中
- protected View findViewTraversal(int id) {
- if (id == mID) {
- return this;
- }
-
- final View[] where = mChildren;
- final int len = mChildrenCount;
-
- for (int i = 0; i < len; i++) {
- View v = where[i];
-
- if ((v.mPrivateFlags & IS_ROOT_NAMESPACE) == 0) {
- v = v.findViewById(id);
-
- if (v != null) {
- return v;
- }
- }
- }
-
- return null;
- }
四。通过activity的setContentView方法和findViewById获取一个view的实例。
它是通过
getWindow().setContentView(layoutResID);设置window对象的view
再来看看window对象是在哪里获得到的,在类Activity中找到
mWindow = PolicyManager.makeNewWindow(this);
它是由PolicyManager生成的。
找到com.android.internal.policy.PolicyManager,找到方法
-
-
- public static Window makeNewWindow(Context context) {
- return sPolicy.makeNewWindow(context);
- }
-
-
- private static final String POLICY_IMPL_CLASS_NAME =
- "com.android.internal.policy.impl.Policy";
-
- private static final IPolicy sPolicy;
-
- static {
-
- try {
- Class policyClass = Class.forName(POLICY_IMPL_CLASS_NAME);
- sPolicy = (IPolicy)policyClass.newInstance();
- } catch (ClassNotFoundException ex) {
- throw new RuntimeException(
- POLICY_IMPL_CLASS_NAME + " could not be loaded", ex);
- } catch (InstantiationException ex) {
- throw new RuntimeException(
- POLICY_IMPL_CLASS_NAME + " could not be instantiated", ex);
- } catch (IllegalAccessException ex) {
- throw new RuntimeException(
- POLICY_IMPL_CLASS_NAME + " could not be instantiated", ex);
- }
- }
找到com.android.internal.policy.impl.Policy类
- public PhoneWindow makeNewWindow(Context context) {
- return new PhoneWindow(context);
- }
它其实是一个phoneWindow对象,继承自window对象
找到com.android.internal.policy.impl.phoneWindow 看它内部是如何把resourceid加载成一个view的
- private ViewGroup mContentParent;
- private DecorView mDecor;
-
-
- @Override
- public void setContentView(int layoutResID) {
- if (mContentParent == null) {
- installDecor();
- } else {
- mContentParent.removeAllViews();
- }
- mLayoutInflater.inflate(layoutResID, mContentParent);
- final Callback cb = getCallback();
- if (cb != null) {
- cb.onContentChanged();
- }
- }
-
-
- private void installDecor() {
- if (mDecor == null) {
- mDecor = generateDecor();
- mDecor.setDescendantFocusability(ViewGroup.FOCUS_AFTER_DESCENDANTS);
- mDecor.setIsRootNamespace(true);
- }
- if (mContentParent == null) {
- mContentParent = generateLayout(mDecor);
-
- mTitleView = (TextView)findViewById(com.android.internal.R.id.title);
- if (mTitleView != null) {
- if ((getLocalFeatures() & (1 << FEATURE_NO_TITLE)) != 0) {
- View titleContainer = findViewById(com.android.internal.R.id.title_container);
- if (titleContainer != null) {
- titleContainer.setVisibility(View.GONE);
- } else {
- mTitleView.setVisibility(View.GONE);
- }
- if (mContentParent instanceof FrameLayout) {
- ((FrameLayout)mContentParent).setForeground(null);
- }
- } else {
- mTitleView.setText(mTitle);
- }
- }
- }
- }
-
-
- protected DecorView generateDecor() {
- return new DecorView(getContext(), -1);
- }
-
-
- protected ViewGroup generateLayout(DecorView decor) {
-
-
-
- mDecor.startChanging();
-
- View in = mLayoutInflater.inflate(layoutResource, null);
- decor.addView(in, new ViewGroup.LayoutParams(MATCH_PARENT, MATCH_PARENT));
-
- ViewGroup contentParent = (ViewGroup)findViewById(ID_ANDROID_CONTENT);
- if (contentParent == null) {
- throw new RuntimeException("Window couldn‘t find content container view");
- }
- return contentParent;
- }
-
-
- private final class DecorView extends FrameLayout implements RootViewSurfaceTaker {
- public DecorView(Context context, int featureId) {
- super(context);
- mFeatureId = featureId;
- }
- }
-
-
-
-
- @Override
- public final View getDecorView() {
- if (mDecor == null) {
- installDecor();
- }
- return mDecor;
- }
-
android2.3 View视图框架源码分析之一:android是如何创建一个view的?
标签:des android http color io os ar 使用 java
原文地址:http://www.cnblogs.com/Free-Thinker/p/4048551.html