setContentView源码解读

源码版本:Android 10

将布局文件id通过setContentView方法传递给父类AppCompatActivity,此处源码如下:
	@Override
    public void setContentView(@LayoutRes int layoutResID) {
        getDelegate().setContentView(layoutResID);
    }

getDelegate()方法最终将会创建AppCompatDelegateImpl对象,该方法源码如下:

 public AppCompatDelegate getDelegate() {
        if (mDelegate == null) {
            mDelegate = AppCompatDelegate.create(this, this);
        }
        return mDelegate;
    }

AppCompatDelegate中的create方法源码如下:

 public static AppCompatDelegate create(Activity activity, AppCompatCallback callback) {
        return new AppCompatDelegateImpl(activity, activity.getWindow(), callback);
    }

由此可知在自定义Activity调用setContentView方法最终调用的是AppCompatDeleagteImpl中的
setContentView方法,该方法源码如下:

 @Override
    public void setContentView(int resId) {
    	//检查mSubDecor是否创建,在ensureSubDecor方法中将布局与window结合起来
        ensureSubDecor();
        //从mSubDecor中找到android.R.id.content对应的ViewGroup
        ViewGroup contentParent = (ViewGroup) mSubDecor.findViewById(android.R.id.content);
        contentParent.removeAllViews();
        //最关键的地方::将自定义Activity的布局id以及找到的ViewGroup传入到LayoutInflater进行操作
        LayoutInflater.from(mContext).inflate(resId, contentParent);
        mOriginalWindowCallback.onContentChanged();
    }

ensureSubDecor()方法源码如下:

 private void ensureSubDecor() {
        if (!mSubDecorInstalled) {
            mSubDecor = createSubDecor();
            //....
        }
    }

 private ViewGroup createSubDecor() {
      	//....
        // 将生成的subDecor与Window绑定,之后就可以通过mWindow根据控件id寻找控件了
        mWindow.setContentView(subDecor)
        return subDecor;
    }

上述方法中最关键地方最终将会调用LayoutInflater中的inflate(三个参数)方法,该方法源码如下所示:

  public View inflate(@LayoutRes int resource, @Nullable ViewGroup root, boolean attachToRoot) {
        final Resources res = getContext().getResources();
        if (DEBUG) {
            Log.d(TAG, "INFLATING from resource: \"" + res.getResourceName(resource) + "\" ("
                  + Integer.toHexString(resource) + ")");
        }
		//查看是否存在预编译布局,一般情况该方法返回的都是空
        View view = tryInflatePrecompiled(resource, res, root, attachToRoot);
        if (view != null) {
            return view;
        }
        //获取xml解析器
        XmlResourceParser parser = res.getLayout(resource);
        try {
        //开始解析布局文件
            return inflate(parser, root, attachToRoot);
        } finally {
            parser.close();
        }
    }

上述开始解析布局文件的inflate方法源码如下所示:

  public View inflate(XmlPullParser parser, @Nullable ViewGroup root, boolean attachToRoot) {
        synchronized (mConstructorArgs) {
         //....
                advanceToRootNode(parser);
                final String name = parser.getName();
                if (TAG_MERGE.equals(name)) {
                    if (root == null || !attachToRoot) {
                        throw new InflateException(" can be used only with a valid "
                                + "ViewGroup root and attachToRoot=true");
                    }

                    rInflate(parser, root, inflaterContext, attrs, false);
                } else {
                    // 根据解析出的tag创建相应view
                    final View temp = createViewFromTag(root, name, inflaterContext, attrs);
                    ViewGroup.LayoutParams params = null;
                    if (root != null) {
                        params = root.generateLayoutParams(attrs);
                        if (!attachToRoot) {
                            // Set the layout params for temp if we are not
                            // attaching. (If we are, we use addView, below)
                            temp.setLayoutParams(params);
                        }
                    }
                    // 解析相应view下面是否还有子控件
                    rInflateChildren(parser, temp, attrs, true);

                    if (root != null && attachToRoot) {
                        root.addView(temp, params);
                    }

                
                    if (root == null || !attachToRoot) {
                        result = temp;
                    }
                }

          //....

            return result;
        }
    }

上述rInflateChildren将会调用rInflate方法,源码如下所示:

 void rInflate(XmlPullParser parser, View parent, Context context,
            AttributeSet attrs, boolean finishInflate) throws XmlPullParserException, IOException {

          //....

        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();
            //针对类似“merge、include”标签的处理    
            if (TAG_REQUEST_FOCUS.equals(name)) {
                pendingRequestFocus = true;
                consumeChildElements(parser);
            } else if (TAG_TAG.equals(name)) {
                parseViewTag(parser, parent, attrs);
            } else if (TAG_INCLUDE.equals(name)) {
                if (parser.getDepth() == 0) {
                    throw new InflateException(" cannot be the root element");
                }
                parseInclude(parser, context, parent, attrs);
            } else if (TAG_MERGE.equals(name)) {
                throw new InflateException(" must be the root element");
            } else {
                //大部分情况还是从这里走
                final View view = createViewFromTag(parent, name, context, attrs);
                final ViewGroup viewGroup = (ViewGroup) parent;
                final ViewGroup.LayoutParams params = viewGroup.generateLayoutParams(attrs);
                //继续调用该方法,填充子控件
                rInflateChildren(parser, view, attrs, true);
                viewGroup.addView(view, params);
            }
        }

     //....
    }

上述createViewFromTag方法源码如下:

  View createViewFromTag(View parent, String name, Context context, AttributeSet attrs,
            boolean ignoreThemeAttr) {
       //....
            //通过传入的控件名称,判断是否符合系统帮忙定义的控件,如果符合系统将帮忙创建
            //最终调用AppCompatViewInflater中的createView方法
            View view = tryCreateView(parent, name, context, attrs);

            if (view == null) {
                final Object lastContext = mConstructorArgs[0];
                mConstructorArgs[0] = context;
                try {
                    //控件名称中不包含“.”
                    if (-1 == name.indexOf('.')) {
                    	//我是从这里分析的
                        view = onCreateView(context, parent, name, attrs);
                    } else {
                        view = createView(context, name, null, attrs);
                    }
                } finally {
                    mConstructorArgs[0] = lastContext;
                }
            }

            return view;
       //....

    }

上述我是从这里分析的所用的onCreateView方法最终会调用create方法,该方法源码如下所示:

 @Nullable
    public final View createView(@NonNull Context viewContext, @NonNull String name,
            @Nullable String prefix, @Nullable AttributeSet attrs)
            throws ClassNotFoundException, InflateException {
       
        //....
            Trace.traceBegin(Trace.TRACE_TAG_VIEW, name);
        //通过反射创建控件    
                final View view = constructor.newInstance(args);
                if (view instanceof ViewStub) {
                    // Use the same context when inflating ViewStub later.
                    final ViewStub viewStub = (ViewStub) view;
                    viewStub.setLayoutInflater(cloneInContext((Context) args[0]));
                }
                return view;
        //....
    }

之后就是重复调用上面的方法从而解析完布局内容,完成自定义Activity中控件的填充。

setContentView时序图

你可能感兴趣的:(Android技巧-源码分析)