(1)setContentView源码分析

一、概述

setContenView()是用来给activity设置布局使用的,但是我们不能只会使用而不深入源码,只有掌握了源码,才能看的更高走的更远。其实分析setContentView的源码就是分析如何将我们设置的布局资源挂载到android.R.id.content上进而形成一个完整的view树的过程

整个view树的结构如下图所示,android.R.layout.screen_simple是其中一种系统布局,具体使用哪个布局需要看我们设置的主题(如透明主题,无标题主题等)

《(1)setContentView源码分析》 setContentView源码-1

二、源码分析

1.调用AppCompatActivity的setContentView()

    @Override
    public void setContentView(@LayoutRes int layoutResID) {
        getDelegate().setContentView(layoutResID);
    }

2.分析下getDelegate()是什么鬼,这里我感觉是代理,封装了具体实现

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

3.看下AppCompatDelegate.create(this, this)做了哪些操作?

  public static AppCompatDelegate create(Activity activity, AppCompatCallback callback) {
        return create(activity, activity.getWindow(), callback);
    }
  private static AppCompatDelegate create(Context context, Window window, AppCompatCallback callback) {
        if (VERSION.SDK_INT >= 24) {
            return new AppCompatDelegateImplN(context, window, callback);
        } else {
            return (AppCompatDelegate)(VERSION.SDK_INT >= 23 ? new AppCompatDelegateImplV23(context, window, callback) : new AppCompatDelegateImplV14(context, window, callback));
        }
    }

create会进行版本判断,>=24会使用AppCompatDelegateImplN,=23会使用AppCompatDelegateImplV23,<23会使用AppCompatDelegateImplV14。
其实我们查看这些imp实现代码,发现都是会调用父类AppCompatDelegateImplV9中的setContentView9()方法,我们就拿v9来做分析。

4.查看AppCompatDelegateImplV9中的setContentView()方法。

public void setContentView(int resId) {
        this.ensureSubDecor();//步骤1
        ViewGroup contentParent = (ViewGroup)this.mSubDecor.findViewById(16908290);//步骤2
        contentParent.removeAllViews();
        LayoutInflater.from(this.mContext).inflate(resId, contentParent);//步骤3
        this.mOriginalWindowCallback.onContentChanged();
    }

4.1 我将上述代码分为三个步骤,先来看下步骤1this.ensureSubDecor(),看名字应该是确保DecorView初始化的。

 private void ensureSubDecor() {
        if (!this.mSubDecorInstalled) {
            this.mSubDecor = this.createSubDecor();
            CharSequence title = this.getTitle();
            if (!TextUtils.isEmpty(title)) {
                this.onTitleChanged(title);
            }

            this.applyFixedSizeWindow();
            this.onSubDecorInstalled(this.mSubDecor);
            this.mSubDecorInstalled = true;
            AppCompatDelegateImplV9.PanelFeatureState st = this.getPanelState(0, false);
            if (!this.isDestroyed() && (st == null || st.menu == null)) {
                this.invalidatePanelMenu(108);
            }
        }

    }

我们主要关注this.mSubDecor = this.createSubDecor()这句代码。

 private ViewGroup createSubDecor() {
       //...代码较多已省略
       this.mWindow.getDecorView();
       subDecor = (ViewGroup)inflater.inflate(layout.abc_screen_simple, (ViewGroup)null);
       return subDecor;
 }

往下走,看下PhoneWindow中的getDecorView()方法

@Override
    public final View getDecorView() {
        if (mDecor == null) {
            installDecor();
        }
        return mDecor;
    }

看下PhoneWindow中的installDecor()只是初始化DecorView,然后执行generateLayout()

 private void installDecor() {
        if (mDecor == null) {
            //获取DecorView,然后他是一个FrameLayout
            mDecor = generateDecor();
            mDecor.setIsRootNamespace(true);
        }
       if (mContentParent == null) {
//初始化mContentParent 对象
            mContentParent = generateLayout(mDecor);
        }
}
protected DecorView generateDecor(int featureId) {
   // System process doesn't have application context and in that case we need to directly use
        // the context we have. Otherwise we want the application context, so we don't cling to the
        // activity.
        Context context;
      .......
        return new DecorView(context, featureId, this, getAttributes());
}

generateLayout我的理解是在decorView上根据不同的系统样式设置不同的布局

protected ViewGroup generateLayout(DecorView decor) {
        // Apply data from current theme.
//首先通过WindowStyle中设置的各种属性,对Window进行requestFeature或者setFlags  
        TypedArray a = getWindowStyle();

        mIsFloating = a.getBoolean(R.styleable.Window_windowIsFloating, false);
//中间省略一些代码
.................
        // Inflate the window decor.

        int layoutResource;
        int features = getLocalFeatures();
        // System.out.println("Features: 0x" + Integer.toHexString(features));
        if ((features & (1 << FEATURE_SWIPE_TO_DISMISS)) != 0) {
            layoutResource = R.layout.screen_swipe_dismiss;
        } else if ((features & ((1 << FEATURE_LEFT_ICON) | (1 << FEATURE_RIGHT_ICON))) != 0) {
            if (mIsFloating) {
                TypedValue res = new TypedValue();
                getContext().getTheme().resolveAttribute(
                        R.attr.dialogTitleIconsDecorLayout, res, true);
                layoutResource = res.resourceId;
            } else {
                layoutResource = R.layout.screen_title_icons;
            }
            // XXX Remove this once action bar supports these features.
            removeFeature(FEATURE_ACTION_BAR);
            // System.out.println("Title Icons!");
        } else if ((features & ((1 << FEATURE_PROGRESS) | (1 << FEATURE_INDETERMINATE_PROGRESS))) != 0
                && (features & (1 << FEATURE_ACTION_BAR)) == 0) {
            // Special case for a window with only a progress bar (and title).
            // XXX Need to have a no-title version of embedded windows.
            layoutResource = R.layout.screen_progress;
            // System.out.println("Progress!");
        } else if ((features & (1 << FEATURE_CUSTOM_TITLE)) != 0) {
            // Special case for a window with a custom title.
            // If the window is floating, we need a dialog layout
            if (mIsFloating) {
                TypedValue res = new TypedValue();
                getContext().getTheme().resolveAttribute(
                        R.attr.dialogCustomTitleDecorLayout, res, true);
                layoutResource = res.resourceId;
            } else {
                layoutResource = R.layout.screen_custom_title;
            }
            // XXX Remove this once action bar supports these features.
            removeFeature(FEATURE_ACTION_BAR);
        } else if ((features & (1 << FEATURE_NO_TITLE)) == 0) {
            // If no other features and not embedded, only need a title.
            // If the window is floating, we need a dialog layout
            if (mIsFloating) {
                TypedValue res = new TypedValue();
                getContext().getTheme().resolveAttribute(
                        R.attr.dialogTitleDecorLayout, res, true);
                layoutResource = res.resourceId;
            } else if ((features & (1 << FEATURE_ACTION_BAR)) != 0) {
                layoutResource = a.getResourceId(
                        R.styleable.Window_windowActionBarFullscreenDecorLayout,
                        R.layout.screen_action_bar);
            } else {
                layoutResource = R.layout.screen_title;
            }
            // System.out.println("Title!");
        } else if ((features & (1 << FEATURE_ACTION_MODE_OVERLAY)) != 0) {
            layoutResource = R.layout.screen_simple_overlay_action_mode;
        } else {
            // Embedded, so no decoration is needed.
            layoutResource = R.layout.screen_simple;
            // System.out.println("Simple!");
        }
//前方高能请注意!!!!!!!!!!!!!
        mDecor.startChanging();
        mDecor.onResourcesLoaded(mLayoutInflater, layoutResource);
..............
        mDecor.finishChanging();

        return contentParent;
    }

根据不同的主题设置完布局之后,看下mDecor.onResourcesLoaded(mLayoutInflater, layoutResource)方法,其实这个地方我们可以猜想一下:就是把传进来的layoutResource通过mLayoutInflater添加到decorView中。

void onResourcesLoaded(LayoutInflater inflater, int layoutResource) {
        mStackId = getStackId();

        if (mBackdropFrameRenderer != null) {
            loadBackgroundDrawablesIfNeeded();
            mBackdropFrameRenderer.onResourcesLoaded(
                    this, mResizingBackgroundDrawable, mCaptionBackgroundDrawable,
                    mUserCaptionBackgroundDrawable, getCurrentColor(mStatusColorViewState),
                    getCurrentColor(mNavigationColorViewState));
        }
//这个我猜想是快照,应该不需要考虑,mDecorCaptionView应该会为null
        mDecorCaptionView = createDecorCaptionView(inflater);
//看重点,这句就是inflate出我们的布局
        final View root = inflater.inflate(layoutResource, null);
        if (mDecorCaptionView != null) {
            if (mDecorCaptionView.getParent() == null) {
                addView(mDecorCaptionView,
                        new ViewGroup.LayoutParams(MATCH_PARENT, MATCH_PARENT));
            }
            mDecorCaptionView.addView(root,
                    new ViewGroup.MarginLayoutParams(MATCH_PARENT, MATCH_PARENT));
        } else {

            //最后addView应该是会执行这个
            addView(root, 0, new ViewGroup.LayoutParams(MATCH_PARENT, MATCH_PARENT));
        }
        mContentRoot = (ViewGroup) root;
        initializeElevation();
    }

到目前为止4中的第一个步骤已经通过4.1讲解完成。其实4.1的整个过程只是初始化DecorView,并且初始化DecorView中的那个LinearLayout。

4.2
4.1中讲的是下边代码中步骤1的内容,其实就是初始化DecorView及其中的LinearLayout,接下来是步骤2和步骤3`

public void setContentView(int resId) {
        this.ensureSubDecor();//步骤1
        ViewGroup contentParent = (ViewGroup)this.mSubDecor.findViewById(16908290);//步骤2
        contentParent.removeAllViews();
        LayoutInflater.from(this.mContext).inflate(resId, contentParent);//步骤3
        this.mOriginalWindowCallback.onContentChanged();
    }

ViewGroup contentParent = (ViewGroup)this.mSubDecor.findViewById(16908290);//步骤2
,mSubDecor看名字我们应该也能知道是decorView中的那个LinearLayout。
所以contentParent拿到的是id为android.R.id.content的frameLayout,及下图中的ContentView。

《(1)setContentView源码分析》 setContentView源码-1

4.3 LayoutInflater.from(this.mContext).inflate(resId, contentParent);//步骤3
步骤3是setContentView源码的最后一步,把我们设置的resId设置到contentParent

5.总结

整个流程其实比较简单:
1.初始化decorView
2.根据不同主题给decorView设置不同的LinearLayout
3.将我们的resId通过layoutInflate.inflate()的方式添加到LinearLayout中的android.R.id.content中。

6.反思

1中的getDelegate().setContentView()这种代理,或者说隐藏代码细节的方式值得我们学习。

源码到此为止,由于篇幅有限,4.3中的LayoutInflater.from(this.mContext).inflate(resId, contentParent)放到下一章来讲。

    原文作者:鲨鱼也疯狂
    原文地址: https://www.jianshu.com/p/46c03cc1b3a2
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞