Window、Activity、DecorView以及ViewRoot的关系

Window、Activity、DecorView 以及 ViewRoot

一、职能简介

Activity

Activity 并不负责视图控制,它只是控制生命周期和处理事件。真正控制视图的是 Window。一个 Activity 包含了一个 Window,Window 才是代表一个窗口。Activity 就像一个控制其,统筹视图的添加和显示,以及通过其他回调方法,来与 Window、以及 View 进行交互

Window

Window 是视图的承载器,内部持有一个 DecorView,而这个 DecorView 才是 View 的根布局。Window 是一个抽象类,实际在 Activity 中持有的是其子类 PhoneWindow。

PhoneWindow 中有个内部类 DecorView,通过创建 DecorView 来加载 Activity 中设置的布局R.layout.activity_main。Window 通过 WindowManager 将 DecorView 加载其中,并将 DecorView 交给 ViewRoot,进行视图绘制以及其他交互。

DecorView

DecorView 是 FrameLayout 的子类,它可以被认为是 Android 视图树的根节点视图。DecorView 作为顶级 View,一般情况下它内部包含一个竖直方向的 LinearLayout,在这个 LinearLayout 里面有上中下三个部分,上面是个 ViewStub,延迟加载的视图(应该是设置 ActionBar,根据 Theme 设置),中间是标题栏(根据 Theme 设置,有的布局没有),下面的是内容栏。具体情况和 Android 版本及主体有关。

在 Activity 中 通过setContentView()所设置的布局文件其实就是被加载到内容栏之中。

1
2
3
4
5
6
7
<LinearLayout>
<!-- Popout bar for action modes -->
<ViewStub .../>
<FrameLayout .../>
<FrameLayout android:id="@android:id/content"
... />
</LinearLayout>
1
2
ViewGroup content = (ViewGroup)findViewById(android.R.id.content);
ViewGroup rootView = (ViewGroup)content.getChildAt(0);

ViewRoot

ViewRoot 对应 ViewRootImpl 类,它是连接 WindowManagerService 和 DecorView 的纽带,View 的三大流程(测量measure、布局layout、绘制draw)均通过 ViewRoot 来完成。

ViewRoot 并不属于 View 树的一份子。从源码实现上来看,它既非 View 的子类,也非 View 的父类,但是,它实现了 ViewParent 接口,这让它可以作为 View 的名义上的父视图

ViewRoot 继承了 Handler 类,可以接收事件并分发,Android 所有的触屏事件、按键事件、界面刷新等事件都是通过 ViewRoot 进行分发的。

结构关系

二、DecorView 的创建

DecorView 是怎么一层层嵌套在 Activity,PhoneWindow 中的,以及 DevorView 如何加载内部布局?

setContentView()

1
2
3
4
public void setContentView(@LayoutRes int layoutResID){
getWindow().setContentView(layoutResID);
initWindowDecorActionBar();
}

setContentView()实际是交给 Window 装载视图,Activity 是怎么获得 Window 对象的?

attach()

1
2
3
4
5
6
7
8
9
final void attach(Context context, ActivityThread aThread, Instrumentation instr, IBinder token, int ident, Application application, Intent intent, ActivityInfo info, CharSequence title, Activity parent, String id, NonConfigurationInstances lastNonConfigurationInstances, Configuration config, String referrer, IVoiceInteractor voiceInteractor, Window window){
...
mWindow = new PhoneWindow(this, window); //创建一个 Window 对象
mWindow.setWindowControllerCallback(this);
mWindow.setCallback(this); // 设置回调,向 Activity 分发点击或状态改变等事件
mWindow.setOnWindowDismissedCallback(this);
... mWindow.setWindowManager((WindowManager)context.getSystemService(Context.WINDOW_SERVICE), mToken, mComponent.flattenToString(), (info.flags & ActivityInfo.FLAG_HARDWARE_ACCELERATED) != 0); //给 Window 设置 WindowManager 对象
...
}

在 Activity 中的attach()中,生成了 PhoneWindow 实例。既然有了 Window 对象,那么就可以设置 DecorView 给 Window 对象了。

attach()->getWindow().setContentView()->PhoneWindow:setContentView()

1
2
3
4
5
6
7
8
9
10
11
12
public void setContentView(int layoutResID){
if(mContentParent == null){ //mContentParent 为空,创建一个 DecorView
installDecor();
}else{
mContentParent.removeAllViews(); //删除其中的 View
}
mLayoutInflater.inflate(layoutResID, mContentParent); // 为 mContentParent 添加子 View, 即 Activity 中设置的布局文件
final Callback cb = getCallback();
if(cb != null && !isDestroyed()){
cb.onContentChanged(); //回调通知,内容改变
}
}

mContentParent 就是前面布局中@android:id/content所对应的 FrameLayout。

先在 PhoneWindow 中创建一个 DecorView,其中创建的过程中可能根据 Theme 不同,加载不同的布局格式,例如有没有 Title,或有没有 ActionBar 等,然后再向 mContentParent 中加入子 View,即 Activity 中设置的布局。到此,视图一层层嵌套添加上了。

那么怎么创建 DecorView 呢?

installDecor()

1
2
3
4
5
6
7
8
9
10
11
12
13
private void installDecor(){
if(mDecor == null){
mDecor = genereateDecor(); //生成 DecorView
mDevor.setDescendantFocusability(ViewGroup.FOCUS_AFTER_DESCENDANTS);
mDecor.setIsRootNamespace(true);
if(!mInvalidatePanelMenuPosted && mInvalidatePanelMenuFeatures != 0){
mDecor.postOnAnimation(mInvalidatePanelMenuRunnable);
}
}
if(mContentParent == null){
mContentParent = generateLayout(mDecor); //为 DecorView 设置布局格式,并返回 mContentParent
}
}
1
2
3
protected DecorView generateDecor(){
return new DecorView(getContext(), -1);
}

generateLayout()

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
protected ViewGroup generateLayout(DecorView decor){
// 从主题文件中获取样式信息
TypedArray a = getWindowStyle();
...
if(a.getBoolean(R.styleable.Window_windowNotitle, false)){
requestFeature(FEATURE_NO_TITLE);
}else if(a.getBoolean(R.styleable.Window_windowActionBar, false)){
requestFeature(FEATURE_ACTION_BAR);
}
...
//根据主题样式,加载窗口布局
int layoutResource;
int features = getLocalFeatures();
if((features & (1 << FEATURE_SWIPE_TO_DISMISS)) != 0){
layoutResource = R.layout.screen_swipe_dismiss;
}else if(...){
...
}

View in = mLayoutInflater.inflate(layoutResource, null); //加载 layoutResource
//往 DecorView 添加子 View,即文章开头介绍 DecorView 时提到的布局格式,那只是一个例子,根据主题样式不同,加载不同的布局
decor.addView(in, new ViewGroup.LayoutParams(MATCH_PARENT, MATCH_PARENT));
mContentRoot = (ViewGroup) in;

ViewGroup contentParent = (ViewGroup)findViewById(ID_ANDROID_CONTENT); //这里获取的就是 mContentParent
if(contentParent == null){
throw new RuntimeException("Window couldn't find content container view");
}

if((features & (1 << FEATURE_INDETERMINATE_PROGRESS)) != 0){
ProgressBar progress = getCircularProgressBar(false);
if(progress != null){
progress.setIndeterminate(true);
}
}

if((features & (1 << FEATURE_SWIPE_TO_DISMISS)) != 0){
registerSwipeCallback();
}
...
return contentParent;
}

先从主题中获取样式,然后根据样式,加载对应布局到 DecorView 中,然后从中获取 mContentParent。获得到之后,就可以后续的为 mContentParent 添加 View,即 Activity 中的布局

三、DecorView 的显示

通过setContentView()设置的界面,为什么在onResume()之后才对用户可见呢?

handleLaunchActivity()

从 ActivityThread 中的 handleLaunchActivity()说起

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
private void handleLaunchActivity(ActivityClientRecord r, Intent customIntent){
//就是在这里调用了 Activity.attach 呀,接着调用了 Activity.onCreate() 和 Activity.onStart()
//但是由于只是初始化了 mDecor,添加了布局文件,
//还没有把 mDecor 添加到负责 UI 显示的 PhoneWindow 中
//所以这时对用户来说还是不可见的
Activity a = performLaunchActivity(r, customIntent);

if(a != null){
handleResumeActivity(r.token, false, r.isForward, !r.activity.mFinished && !r.startsNotResumed);

if(!r.activity.mFinished && r.startsNotResumed){
try{
r.activity.mCalled = false;
mInsrtumentation.callActivityOnPause(r.activity);
}
}
}
}

接着,在handleResumeActivity()中,DecorView 将会显示出来,ViewRoot 也将登场。

handleResumeActivity()

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
final void handleResumeActivity(IBinder token, boolean clearHide, boolean isForward, boolean reallyResume){
//这个时候,Activity.onResume() 已经调用了,但是现在界面还是不可见的
ActivityClientRecord r = performResumeActivity(token, clearHide);

if(r != null){
final Activity a = r.activity;
if(r.window == null && !a.mFinished && willBeVisible){
r.window = r.activity.getWindow();
View decor = r.window.getDecorView();
// decor 对用户不可见
decor.setVisibility(View.INVISIBLE);
ViewManager vm = a.getWindowManager();
WindowManager.LayoutParams l = r.window.getAttributes();
a.mDecor = decor;

l.type = WindowManager.LayoutParams.TYPE_BASE_APPLICATION;

if(a.mVisibleFromClient){
a.mWindowAdded = true;
wm.addView(decor, l); //但是这个时候,还是不可见的
}

if(!r.activity.mFinished && willBeVisible && r.activity.mDecor != null && !r.hideForNow){
if(r.activity.mVisibleFromClient){
//在这里执行了重要的操作,使得 DecorView 可见
r.activity.maleVisible();
}
}
}
}
}

makeVisible()

1
2
3
4
5
6
7
8
void makeVisible(){
if(!mWindowAdded){
ViewManager vm = getWindowManager();
vm.addView(mDecor, getWindow().getAttributes()); // 将 DecorView 添加到 WindowManager
mWindowAdded = true;
}
mDecor.setVisibility(View.VISIBLE); // DecorView 可见!
}

vm.addView(mDecor, getWindow().getAttributes());在其内部创建了一个 ViewRootImpl 对象,负责绘制显示各个子 View.

addView()方法,因为 WindowManager 是个接口,具体是交给 WindowManagerImpl 来实现的

addView()

1
2
3
4
5
6
7
8
public final class WindowManagerImpl implements WindowManager{
private final WindowManagerGlobal mGlobal = WindowManagerGlobal.getInstance();
...
@Override
public void addView(View view, ViewGroup.LayoutParams params){
mGlobal.addView(view, params, mDisplay, mParentWindow);
}
}

再交给 WindowManagerGlobal 的addView()方法实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
public void addView(View view, ViewGroup.LayoutPramas params, Display display, Window parentWindow){
final WindowManager.LayoutParams wparams = (WindowManager.LayoutParams)params;
...
synchronized(mLock){
ViewRootImpl root;
root = new ViewRootImpl(view.getContext(), display);
view.setLayoutParams(wparams);

mViews.add(view);
mRoots.add(root);
mParams.add(wparams);
}
...
try{
// 将 DecorView 交给 ViewRootImpl
root.setView(view, wparams, panelParentView);
}catch(RuntimeException e){

}
}

其中 ViewRootImpl 实例在setView()中通过一系列的操作,最终调用了performTraversals()方法,开始绘制视图树,最终界面才会显示出来。

绘制流程

ViewRootImpl 的作用不止如此,还有许多功能,如事件分发。要知道,当用户点击屏幕产生一个触摸行为,这个触摸行为通过底层硬见来传递捕获,然后就交给了 ViewRootImpl,接着将事件传递给 DecorView,而 DecorView 再交给 PhoneWindow,PhoneWindow 再交给 Activity,然后接下来就是我们常见的 View 事件分发

硬见 -> ViewRootImpl -> DecorView -> PhoneWindow -> Activity

四、总结

Activity 就像个控制器,不负责视图部分。Window 像个承载器,装着内部视图。DecorView 就是个顶层视图,是所有 View 的最外层布局。ViewRoot 像个连接器,负责沟通,通过硬件的感知来通知视图,进行用户之间的交互。


参考引用

简析Window、Activity、DecorView以及ViewRoot之间的错综关系