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("<merge /> can be used only with a valid "
                                + "ViewGroup root and attachToRoot=true");
                    }

                    rInflate(parser, root, inflaterContext, attrs, false);
                } else {
                	// Temp is the root view that was found in the xml(Temp是在当前xml文件中的根View)
                  	//createViewFromTag很重要,是分析插件化换肤的入口
                    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;
        }
    }

上述createViewFromTag方法源码如下所示:

 private View createViewFromTag(View parent, String name, Context context, AttributeSet attrs) {
    return createViewFromTag(parent, name, context, attrs, false);
 }

 View createViewFromTag(View parent, String name, Context context, AttributeSet attrs,
            boolean ignoreThemeAttr) {
        if (name.equals("view")) {
            name = attrs.getAttributeValue(null, "class");
        }

        // Apply a theme wrapper, if allowed and one is specified.
        if (!ignoreThemeAttr) {
            final TypedArray ta = context.obtainStyledAttributes(attrs, ATTRS_THEME);
            final int themeResId = ta.getResourceId(0, 0);
            if (themeResId != 0) {
                context = new ContextThemeWrapper(context, themeResId);
            }
            ta.recycle();
        }

        try {
            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;
        } catch (InflateException e)  {
            //....省略一些不相干的代码
        }
    }

    public final View tryCreateView(@Nullable View parent, @NonNull String name,
        @NonNull Context context,
        @NonNull AttributeSet attrs) {
        //...隐藏一些不相干的代码
        //可以通过反射的方式修改mFactory2,从而实现换肤插件
        try {
            View view;
            //由于一些初始化操作,mFactory2运行到此处时不为空
            if (mFactory2 != null) {
             //最终调用AppCompatViewInflater中的createView方法,但是只支持生成部分控件
             //不过可以通过自定义mFactory2让其生成用户所需要的控件
                view = mFactory2.onCreateView(parent, name, context, attrs);
            } else if (mFactory != null) {
                view = mFactory.onCreateView(name, context, attrs);
            } else {
                view = null;
            }

            //...隐藏一些不相干的代码
            return view;
        } catch (InflateException e){
            //...隐藏一些不相干的代码
        } 
    }

上述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("<include /> cannot be the root element");
                }
                parseInclude(parser, context, parent, attrs);
            } else if (TAG_MERGE.equals(name)) {
                throw new InflateException("<merge /> 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时序图

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值