setContentView()方法探究

作者: 问荆_ | 来源:发表于2019-05-07 10:38 被阅读0次
    image.png

    加载流程

    这里简单介绍一下

    Window

    即窗口。我们平常接触的都是应用Window,它对应一个Activity,其本身是一个抽象的概念,在Android中的具体表现就是android.view.Window这个抽象类,具体的实现类就是PhoneWindow

    在Android系统中,窗口是独占一个Surface(屏幕缓存区)实例的显示区域,每个窗口的Surface由WindowManagerService分配。创建Window的过程就是WindowManagerService分配Surface的过程。

    窗口这个类中最核心的三个部分是:

    • WindowManager.LayoutParams: 窗口的布局参数;

    • Callback: 窗口的回调接口,通常由Activity实现;

    • 通过一系列方法关联控件树如:setContentView()

    愉快的源码 o(╥﹏╥)o

    我们从Activity开始:

    新建一个Activity:

    public class Main2Activity extends AppCompatActivity {
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            // 从这一行开始
            setContentView(R.layout.activity_main2);
        }
    }
    

    我们看见了一个熟悉的方法 setContentView(),进去看看:

    @Override
        public void setContentView(@LayoutRes int layoutResID) {
            getDelegate().setContentView(layoutResID);
        }
    
        @Override
        public void setContentView(View view) {
            getDelegate().setContentView(view);
        }
    
        @Override
        public void setContentView(View view, ViewGroup.LayoutParams params) {
            getDelegate().setContentView(view, params);
        }
    

    这里有一系列的重载方法,都通过 getDelegate()方法获得了 AppCompatDelegate对象,再调用了 AppCompatDelegate的setContentView()方法。问题来了什么是AppCompatDelegate?
    我们看看官方的说明:

    This class represents a delegate which you can use to extend AppCompat's support to any

    • {@link android.app.Activity}.

    简单解释一下: 此类表示一个委托,您可以使用该委托将AppCompat的支持扩展到任何活动。
    但是注意一个活动只能被一个AppCompatDelegate连接。

    我们去看看AppCompatDelegate调用setContentView()方法干了什么:

     @Override
        public void setContentView(View v) {
            ensureSubDecor();
            ViewGroup contentParent = (ViewGroup) mSubDecor.findViewById(android.R.id.content);
            contentParent.removeAllViews();
            contentParent.addView(v);
            mOriginalWindowCallback.onContentChanged();
        }
    
        @Override
        public void setContentView(int resId) {
            ensureSubDecor();
            ViewGroup contentParent = (ViewGroup) mSubDecor.findViewById(android.R.id.content);
            contentParent.removeAllViews();
            LayoutInflater.from(mContext).inflate(resId, contentParent);
            mOriginalWindowCallback.onContentChanged();
        }
    
        @Override
        public void setContentView(View v, ViewGroup.LayoutParams lp) {
            ensureSubDecor();
            ViewGroup contentParent = (ViewGroup) mSubDecor.findViewById(android.R.id.content);
            contentParent.removeAllViews();
            contentParent.addView(v, lp);
            mOriginalWindowCallback.onContentChanged();
        }
    

    这里调用了一个方法ensureSubDecor(),我们看看这个方法干了什么

     private void ensureSubDecor() {
            if (!mSubDecorInstalled) {
                mSubDecor = createSubDecor();
    
                // If a title was set before we installed the decor, propagate it now
                CharSequence title = getTitle();
                if (!TextUtils.isEmpty(title)) {
                    onTitleChanged(title);
                }
    
                applyFixedSizeWindow();
    
                onSubDecorInstalled(mSubDecor);
    
                mSubDecorInstalled = true;
    
                PanelFeatureState st = getPanelState(FEATURE_OPTIONS_PANEL, false);
                if (!isDestroyed() && (st == null || st.menu == null)) {
                    invalidatePanelMenu(FEATURE_SUPPORT_ACTION_BAR);
                }
            }
        }
    

    这里通过createSubDecor()方法创建了mSubDecor,那mSubDecor是什么呢?其实mSubDecor是一个ViewGroup。

    接下来我们看看createSubDecor()方法:这个方法有点长我们分段看看

    第一段

     TypedArray a = mContext.obtainStyledAttributes(R.styleable.AppCompatTheme);
    
            if (!a.hasValue(R.styleable.AppCompatTheme_windowActionBar)) {
                a.recycle();
                throw new IllegalStateException(
                        "You need to use a Theme.AppCompat theme (or descendant) with this activity.");
            }
    
            if (a.getBoolean(R.styleable.AppCompatTheme_windowNoTitle, false)) {
                requestWindowFeature(Window.FEATURE_NO_TITLE);
            } else if (a.getBoolean(R.styleable.AppCompatTheme_windowActionBar, false)) {
                // Don't allow an action bar if there is no title.
                requestWindowFeature(FEATURE_SUPPORT_ACTION_BAR);
            }
            if (a.getBoolean(R.styleable.AppCompatTheme_windowActionBarOverlay, false)) {
                requestWindowFeature(FEATURE_SUPPORT_ACTION_BAR_OVERLAY);
            }
            if (a.getBoolean(R.styleable.AppCompatTheme_windowActionModeOverlay, false)) {
                requestWindowFeature(FEATURE_ACTION_MODE_OVERLAY);
            }
            mIsFloating = a.getBoolean(R.styleable.AppCompatTheme_android_windowIsFloating, false);
            a.recycle();
    
            // Now let's make sure that the Window has installed its decor by retrieving it
            mWindow.getDecorView();
    

    我们可以看出第一部分是用 TypedArray这种数据结构获取自定义属性集,然后进行一系列判断。 requestWindowFeature()这个方法用来定制与activity关联的PhoneWindow的外观,这里不做分析。

    但是这里有一个重点,看最后一句:

     mWindow.getDecorView();
    

    通过注释我们可以猜测,这句的用处是确保window已经安装了decor。

    我们看看getDecorView()到底,等会再回来。
    这个方法很长,我们先看我们想关注的地方

     mForceDecorInstall = false;
            if (mDecor == null) {
               //mDecor是DecorView,通过下面这个方法创建
                mDecor = generateDecor(-1);
                mDecor.setDescendantFocusability(ViewGroup.FOCUS_AFTER_DESCENDANTS);
                mDecor.setIsRootNamespace(true);
                if (!mInvalidatePanelMenuPosted && mInvalidatePanelMenuFeatures != 0) {
                    mDecor.postOnAnimation(mInvalidatePanelMenuRunnable);
                }
            } else {
                mDecor.setWindow(this);
            }
            if (mContentParent == null) {
                // 结合DecorView的创建,我们可以猜到这行代码的作用
                mContentParent = generateLayout(mDecor);
    
    

    这里我们看见第4行创建DecorView,第15行创建mContentParent。
    我们先看看 generateDecor()这个方法

    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;
            if (mUseDecorContext) {
                Context applicationContext = getContext().getApplicationContext();
                if (applicationContext == null) {
                    context = getContext();
                } else {
                    context = new DecorContext(applicationContext, getContext().getResources());
                    if (mTheme != -1) {
                        context.setTheme(mTheme);
                    }
                }
            } else {
                context = getContext();
            }
            return new DecorView(context, featureId, this, getAttributes());
        }
    

    在这里是直接new的一个DecorView对象。
    接下来我们看看 mContentParent的创建方法generateLayout(mDecor),这里代码也很多我们截取

     mDecor.onResourcesLoaded(mLayoutInflater, layoutResource);
    
            ViewGroup contentParent = (ViewGroup)findViewById(ID_ANDROID_CONTENT);
            if (contentParent == null) {
                throw new RuntimeException("Window couldn't find content container view");
            }
    

    源码中在通过TypedArray获取windowStyle然后进行一系列判断后,再用layoutResource通过一系列判断获取不同的主题的资源,然后在上面第一行中加载到DecorView中。

    再看第三行,通过findViewById()方法获取了id为content的控件,最后返回的也是contentParent。
    所以mContentParent就是contentview

    到这里 mWindow.getDecorView()就分析完了,我们又要返回createSubDecor()方法,看看他下面的操作。

    代码还是很多,我们就关注重点
    第二段

      // Now set the Window's content view with the decor
            mWindow.setContentView(subDecor);
    

    这里调用了window的setContentView()的方法,我们进去看看干了什么,

    @Override
        public void setContentView(View view) {
            setContentView(view, new ViewGroup.LayoutParams(MATCH_PARENT, MATCH_PARENT));
        }
    
        @Override
        public void setContentView(View view, ViewGroup.LayoutParams params) {
            // Note: FEATURE_CONTENT_TRANSITIONS may be set in the process of installing the window
            // decor, when theme attributes and the like are crystalized. Do not check the feature
            // before this happens.
            if (mContentParent == null) {
                installDecor();
            } else if (!hasFeature(FEATURE_CONTENT_TRANSITIONS)) {
                mContentParent.removeAllViews();
            }
    
            if (hasFeature(FEATURE_CONTENT_TRANSITIONS)) {
                view.setLayoutParams(params);
                final Scene newScene = new Scene(mContentParent, view);
                transitionTo(newScene);
            } else {
               //把从参数中传过来的view,加入到mContentParent中
                mContentParent.addView(view, params);
            }
            mContentParent.requestApplyInsets();
            final Callback cb = getCallback();
            if (cb != null && !isDestroyed()) {
                cb.onContentChanged();
            }
            mContentParentExplicitlySet = true;
        }
    

    这里23行就直接把从参数中传过来的view,加入到mContentParent中

    我们再回到最开始,AppCompatDelegate调用的setContentView()方法

        @Override
        public void setContentView(int resId) {
            ensureSubDecor();
            ViewGroup contentParent = (ViewGroup) mSubDecor.findViewById(android.R.id.content);
            contentParent.removeAllViews();
            LayoutInflater.from(mContext).inflate(resId, contentParent);
            //调用window的回调告诉window视图更新了
            mOriginalWindowCallback.onContentChanged();
        }
    

    ensureSubDecor()这个方法结束了。
    我们该去看第六行了,用LayoutInflater填充视图

    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) + ")");
           }
    
           final XmlResourceParser parser = res.getLayout(resource);
           try {
               return inflate(parser, root, attachToRoot);
           } finally {
               parser.close();
           }
       }
    

    这里又调用了inflate(parser, root, attachToRoot),这里面就是填充布局的过程了,就不分析了。
    view的加载流程就基本结束了。

    view的绘制流程

    每个活动的decorView都有一个与之关联的ViewRoot对象(ViewRootImpl),这种关系由WindowManager来维护。

    view绘制的起点

    一般来说初次完成布局的都是通过ViewRootImpl类的requestLayout()方法

      @Override
       public void requestLayout() {
           if (!mHandlingLayoutInLayoutRequest) {
           //检查线程是不是主线程
               checkThread();
               mLayoutRequested = true;
               scheduleTraversals();
           }
       }
    

    这个方法中又调用了ViewRootImpl的scheduleTraversals()的方法,我们去看看

    void scheduleTraversals() {
           if (!mTraversalScheduled) {
               mTraversalScheduled = true;
               mTraversalBarrier = mHandler.getLooper().getQueue().postSyncBarrier();
               mChoreographer.postCallback(
                       Choreographer.CALLBACK_TRAVERSAL, mTraversalRunnable, null);
               if (!mUnbufferedInputDispatch) {
                   scheduleConsumeBatchedInput();
               }
               notifyRendererOfFramePending();
               pokeDrawLockIfNeeded();
           }
       }
    

    这里我们看到 mChoreographer发送了一个回调,该方法会向主线程发送一个“遍历”消息,最终会导致ViewRootImpl的performTraversals()方法被调用。
    在这里面进行了view绘制的三个阶段:

    • 1 measure: 判断是否需要重新计算View的大小,需要的话则计算;
    • 2 layout: 判断是否需要重新计算View的位置,需要的话则计算;
    • 3 draw: 判断是否需要重新绘制View,需要的话则重绘制。

    小白学习笔记暂时分享到这了

    相关文章

      网友评论

        本文标题:setContentView()方法探究

        本文链接:https://www.haomeiwen.com/subject/rwmbhqtx.html