Activity setContentView 流程分析

你真的完全了解setContentView()么?

创建一个 Activity ,系统为我们默认继承 AppCompatActivity,先从分析继承 Activity 的。

继承 Activity 的流程的 setContentView 分析

/**
* 从布局资源中设置活动内容。 该资源将被inflated,将所有顶层视图添加到活动中
*/
public void setContentView(@LayoutRes int layoutResID) {
    // 获取Window 调用window的setContentView方法,发现是抽象类,所以需要找具体的实现类 
    // PhoneWindow
    getWindow().setContentView(layoutResID);
    initWindowDecorActionBar();
}
/**
 * 顶层窗口外观和行为策略的抽象基类。 该类的实例应作为添加到窗口管理器的*  顶层视图。它提供了标准的UI 策略,如背景、标题区域、默认键处理等。
 * 这个抽象类唯一存在的实现是android.view.PhoneWindow,当需要一个Window时,你应该实例化它。
 */
public abstract class Window{

}

在 ActivityThread 的 performLaunchActivity 方法中通过反射创建 Activity,在 onCreate 调用之前会调用 Activity.attach 方法,在 attach 方法里创建 PhoneWindow 对象。

ActivityThread.performLaunchActivity
-->activity.attach
    --> new PhoneWindow()
-->mInstrumentation.callActivityOnCreate

PhoneWindow 并不在 android.view 包里,新版的在 android.internal.policy 下

PhoneWindow.setContentView --- 主要目的  创建 DecorView 拿到 Content

--》 installDecor(); // 创建 DecorView 拿到 mContentParent
    --》 mDecor = generateDecor(-1);
        --》 new DecorView()
    --》 mContentParent = generateLayout(mDecor);
        --》 R.layout.screen_simple --》 @android:id/content --》 mContentParent
        //  R.layout.screen_simple --》 添加到 DecorView(FrameLayout)
        --》 mDecor.onResourcesLoaded(mLayoutInflater, layoutResource);  
        --》 ViewGroup contentParent = (ViewGroup)findViewById(ID_ANDROID_CONTENT);

--》 mLayoutInflater.inflate(layoutResID, mContentParent); //  R.layout.activity_main 渲染到 mContentParent

PhoneWindow.setContentView() 代码分析如下:

    // 主要目的  创建 DecorView 拿到 Content
    @Override
    public void setContentView(int layoutResID) {
        // 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) {
            // 如果mContentParent 等于空,调用 installDecor();
            // 创建 DecorView 拿到 mContentParent
            installDecor();
        } else if (!hasFeature(FEATURE_CONTENT_TRANSITIONS)) {
            mContentParent.removeAllViews();
        }

        if (hasFeature(FEATURE_CONTENT_TRANSITIONS)) {
            final Scene newScene = Scene.getSceneForLayout(mContentParent, layoutResID,
                    getContext());
            transitionTo(newScene);
        } else {
            // 把我们自己的布局layoutId加入到mContentParent,我们set进来的布局原来是放在这里面的
            //  R.layout.activity_main 渲染到 mContentParent
            mLayoutInflater.inflate(layoutResID, mContentParent);
        }
        mContentParent.requestApplyInsets();
        final Callback cb = getCallback();
        if (cb != null && !isDestroyed()) {
            cb.onContentChanged();
        }
        mContentParentExplicitlySet = true;
    }

找到了 setContentView 的根源 ,里面的 installDecor() 方法如下:

    private DecorView mDecor;

    private void installDecor() {    
        if (mDecor == null) {
           // 先去创建一个  DecorView 
           mDecor = generateDecor(-1);
        }
        // ......
    
        if (mContentParent == null) {
           mContentParent = generateLayout(mDecor);
        }
    }
    
    // generateDecor 方法
    protected DecorView generateDecor(int featureId) {
        // 就是new一个DecorView ,DecorView extends FrameLayout 不同版本的源码有稍微的区别,
        // 低版本DecorView 是PhoneWindow的内部类,高版本是一个单独的类
        return new DecorView(context, featureId, this, getAttributes());
    }

    protected ViewGroup generateLayout(DecorView decor) {
        // Inflate the window decor.
        int layoutResource;
        // 都是一些判断,发现 layoutResource = 系统的一个资源文件,
        if(){}else if(){}else if(){
            // Embedded, so no decoration is needed.
            // R.layout.screen_simple --》 @android:id/content --》 mContentParent
            layoutResource = R.layout.screen_simple;
            // System.out.println("Simple!");
        }
        
        mDecor.startChanging();
        // 把布局解析加载到  DecorView 而加载的布局是一个系统提供的布局,不同版本不一样
        // 某些源码是 addView() 其实是一样的
        //  R.layout.screen_simple --》 添加到 DecorView(FrameLayout)
        mDecor.onResourcesLoaded(mLayoutInflater, layoutResource);

        //  ID_ANDROID_CONTENT 是 android.R.id.content,这个View是从DecorView里面去找的,
        //  也就是 从系统的layoutResource里面找一个id是android.R.id.content的一个FrameLayout
        ViewGroup contentParent = (ViewGroup)findViewById(ID_ANDROID_CONTENT);
        
        // 返回
        return contentParent;
    }

下面对流程梳理:

  • Activity 里面设置 setContentView(),其实是调用 PhoneWindow 中的 setContentView(),在 PhoneWindow 中通过 installDecor() 实例化一个 DecorView。(installDecor() 和 setContentView() 都在 PhoneWindow 类中,所以有很多变量是公用的)
  • mDecor = generateDecor(-1); 这句话是实例化一个DecorView 的关键
  • mContentParent = generateLayout(mDecor); 将 mDecor (实例化一个DecorView)传进去进行一系列的系统加工(这里包括是否有头部等系统加工,便很好解决了为什么要在 setContentView() 之前执行设置Window的Flag或者requestWindowFeature()才会起作用)
  • mDecor.onResourcesLoaded(mLayoutInflater, layoutResource); ViewGroup contentParent = (ViewGroup)findViewById(ID_ANDROID_CONTENT);这个就是给 mDecor 添加配置的关键语句,最后通过 return contentParent 返回给 mContentParent(这个是全局变量)
继承Activity示意图
继承Activity示意图

常见问题

  1. 为什么 requestWindowFeature() 要在 setContentView() 之前调用
    requestWindowFeature 实际调用的是 PhoneWindow.requestFeature,在这个方法里面会判断,如果变量 mContentParentExplicitlySet 为 true 则报错,而这个变量会在 PhoneWindow.setContentView 调用的时候设置为 true。
  2. 为什么这么设计呢?
    DecorView 的 xml 布局是通过设置的窗口特征进行选择的。
  3. 为什么 requestWindowFeature(Window.FEATURE_NO_TITLE); 设置无效?
    需要用 supportRequestWindowFeature(Window.FEATURE_NO_TITLE);,因为继承的是 AppCompatActivity,这个类里面会覆盖设置。

继承 AppCompatActivity 的流程的 setContentView 分析

大概流程如下:

AppCompatDelegate.setContentView 
--> ensureSubDecor();
    --> mSubDecor = createSubDecor();
        --> ensureWindow(); // 从Activity 那PhoneWindow
        --> mWindow.getDecorView();
            --> installDecor(); // mContentParent
            。。。 。。。 //看Activity的流程
        // R.layout.screen_simple 里面的 content  ---》 把 content 的 View 复制到 R.id.action_bar_activity_content
        --> final ViewGroup windowContentView = (ViewGroup) mWindow.findViewById(android.R.id.content);
        --> windowContentView.setId(View.NO_ID); // 将原始的 content id 置为 NO_ID
        --> contentView.setId(android.R.id.content); // subDecerView R.id.action_bar_activity_content --> 置为 content
        --> mWindow.setContentView(subDecor); // 
--> ViewGroup contentParent = mSubDecor.findViewById(android.R.id.content);
继承AppCompatActivity示意图

AppCompatActivity 的 setContentView

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

这里获取了一个代理, 然后调用代理的 setContentView 方法,点击 getDelegate 进入

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

进入 AppCompatDelegateImpl.setContentView

    @Override
    public void setContentView(View v) {
        ensureSubDecor();
        ViewGroup contentParent = mSubDecor.findViewById(android.R.id.content);
        contentParent.removeAllViews();
        contentParent.addView(v);
        mAppCompatWindowCallback.getWrapped().onContentChanged();
    }

ensureSubDecor(); 执行完成后, 初始化了 mSubDecor 。接着从 mSubDecor 中获取 id 为 content 的控件, 并转为 ViewGroup。然后把我们传入的资源文件添加到这个 ViewGroup 中去。

进入方法 ensureSubDecor

// true if we have installed a window sub-decor layout.
private boolean mSubDecorInstalled;
private ViewGroup mSubDecor;

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

进入 AppCompatDelegateImpl.createSubDecor()

private ViewGroup createSubDecor() {
//---------------------------------第一部分----------------------------------
    TypedArray a = mContext.obtainStyledAttributes(R.styleable.AppCompatTheme);
    ...
    ...
    a.recycle();

//---------------------------------第二部分----------------------------------
// Now let's make sure that the Window has installed its decor by retrieving it
    // 从Activity 那PhoneWindow
    ensureWindow();
    mWindow.getDecorView();

//---------------------------------第三部分----------------------------------
    final LayoutInflater inflater = LayoutInflater.from(mContext);
    ViewGroup subDecor = null;

    if (!mWindowNoTitle) {
        if (mIsFloating) {
            // If we're floating, inflate the dialog title decor
            subDecor = (ViewGroup) inflater.inflate( R.layout.abc_dialog_title_material, null);
            ...
        } else if (mHasActionBar) {
            ...
            ...
            // Now inflate the view using the themed context and set it as the content view
            subDecor = (ViewGroup) LayoutInflater.from(themedContext).inflate(R.layout.abc_screen_toolbar, null);
            ...
            ...
            ...
        }
    } else {
        if (mOverlayActionMode) {
            subDecor = (ViewGroup) inflater.inflate(R.layout.abc_screen_simple_overlay_action_mode, null);
        } else {
            subDecor = (ViewGroup) inflater.inflate(R.layout.abc_screen_simple, null);
        }

        if (Build.VERSION.SDK_INT >= 21) {
            ...
        } else {
            ...
        }
    }
    if (subDecor == null) {
      }
   ...
   ...
   ...
//---------------------------------第四部分----------------------------------
    final ContentFrameLayout contentView = (ContentFrameLayout) subDecor.findViewById(R.id.action_bar_activity_content);
    final ViewGroup windowContentView = (ViewGroup) mWindow.findViewById(android.R.id.content);
    if (windowContentView != null) {
        while (windowContentView.getChildCount() > 0) {
            final View child = windowContentView.getChildAt(0);
            windowContentView.removeViewAt(0);
            contentView.addView(child);
        }
        windowContentView.setId(View.NO_ID);
        contentView.setId(android.R.id.content);
        ...
        ...
    }

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

    ...
    ...

    return subDecor;
}
createSubDecor() 第一部分

Activity.setContentView 中 TypedArray 是取的是 Window 的, 然后赋值给 PhoneWindow 的;
AppCompatActivity.setContentView 中TypedArray 取的是 AppCompatTheme 的, 然后赋值给 AppCompatDelegateImpl 的

createSubDecor() 第二部分

ensureWindow(); 主要目的 从Activity 那PhoneWindow
进入 ensureWindow 方法

    private void ensureWindow() {
        // We lazily fetch the Window for Activities, to allow DayNight to apply in
        // attachBaseContext
        if (mWindow == null && mHost instanceof Activity) {
            // 从Activity 那PhoneWindow
            attachToWindow(((Activity) mHost).getWindow());
        }
        if (mWindow == null) {
            throw new IllegalStateException("We have not been given a Window");
        }
    }


    private void attachToWindow(@NonNull Window window) {
        if (mWindow != null) {
            throw new IllegalStateException(
                    "AppCompat has already installed itself into the Window");
        }

        .....

        mWindow = window;
    }

mWindow.getDecorView();
进入 PhoneWindow 的 getDecorView() 方法

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

初始化了 DecorView 和 mContentParent.(installDecor() 流程前面已经介绍)

createSubDecor() 第三部分

取了一个 R.layout.abc_screen_simple 的布局 subDecor = (ViewGroup) inflater.inflate(R.layout.abc_screen_simple, null);,可以理解为 AppCompatActivity 特定的根布局。

R.layout.abc_screen_simple 布局文件如下:



    

    



// abc_screen_content_include.xml 


    


PhoneWindow 中给 DecorView 加载了一个 LinearLayout, 里面有两部分, 其中一部分是一个 FrameLayout。
而 AppCompatDelegateImpl 这里, 给 subDecor 赋值了一个 FitWindowsLinearLayout 布局 , 里面也有两部分, 其中一部分是一个 ContentFrameLayout 。

createSubDecor() 第四部分

//---------------------------------第四部分----------------------------------
   // R.layout.screen_simple 里面的 content  ---》 把 content 的 View 复制到 R.id.action_bar_activity_content
    final ContentFrameLayout contentView = (ContentFrameLayout) subDecor.findViewById(R.id.action_bar_activity_content);
    final ViewGroup windowContentView = (ViewGroup) mWindow.findViewById(android.R.id.content);
    if (windowContentView != null) {
        while (windowContentView.getChildCount() > 0) {
            final View child = windowContentView.getChildAt(0);
            windowContentView.removeViewAt(0);
            contentView.addView(child);
        }
        // 将原始的 content id 置为 NO_ID
        windowContentView.setId(View.NO_ID);
        // subDecerView R.id.action_bar_activity_content --> 置为 content
        contentView.setId(android.R.id.content);
        ...
        ...
    }

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

    ...
    ...

    return subDecor;
  1. 先是从 subDecor 中取出一个 ID 为 action_bar_activity_content 的控件赋值给 contentView 变量。这个 ID 就是上面布局文件中的 ContentFrameLayout。
  2. 接着从 PhoneWindow 中的 DecorView 中获取一个 ID 为 content 的 ViewGroup. 赋值给 windowContentView。这个 ID 不就是 DecorView 中 LinearLayout 里面的 FrameLayout 。
  3. 循环遍历 windowContentView, 取出 windowContentView 中每一个子 View, 然后 windowContentView 先删除这个View, 再添加到 ContentFrameLayout 中. 直至windowContentView 为空。
  4. 把 DecorView 中 LinearLayout 里面的 FrameLayout ID 改为 NO_ID。
  5. 把 subDecor 中 ContentFrameLayout ID 改为 R.id.content。
  6. 调用 PhoneWindow 的 setContentView 把 subDecor 加载到 PhoneWindow 中的 mContentParent 中.

你可能感兴趣的:(Activity setContentView 流程分析)