• 一、职能简介
    • Activity
    • Window
    • DecorView
    • ViewRoot
  • 二、DecorView的创建
    • setContentView
  • 三、DecorView的显示
  • 四、总结

    一、职能简介

    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版本及主体有关,以其中一个布局为例,如下所示:

    1. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    2. android:fitsSystemWindows="true"
    3. android:orientation="vertical">
    4. <!-- Popout bar for action modes -->
    5. <ViewStub
    6. android:id="@+id/action_mode_bar_stub"
    7. android:layout_width="match_parent"
    8. android:layout_height="wrap_content"
    9. android:inflatedId="@+id/action_mode_bar"
    10. android:layout="@layout/action_mode_bar"
    11. android:theme="?attr/actionBarTheme" />
    12. <FrameLayout
    13. style="?android:attr/windowTitleBackgroundStyle"
    14. android:layout_width="match_parent"
    15. android:layout_height="?android:attr/windowTitleSize">
    16. <TextView
    17. android:id="@android:id/title"
    18. style="?android:attr/windowTitleStyle"
    19. android:layout_width="match_parent"
    20. android:layout_height="match_parent"
    21. android:background="@null"
    22. android:fadingEdge="horizontal"
    23. android:gravity="center_vertical" />
    24. </FrameLayout>
    25. <FrameLayout
    26. android:id="@android:id/content"
    27. android:layout_width="match_parent"
    28. android:layout_height="0dip"
    29. android:layout_weight="1"
    30. android:foreground="?android:attr/windowContentOverlay"
    31. android:foregroundGravity="fill_horizontal|top" />
    32. </LinearLayout>

    在Activity中通过setContentView所设置的布局文件其实就是被加到内容栏之中的,成为其唯一子View,就是上面的id为content的FrameLayout中,在代码中可以通过content来得到对应加载的布局。

    1. ViewGroup content = (ViewGroup)findViewById(android.R.id.content);
    2. ViewGroup rootView = (ViewGroup) content.getChildAt(0);

    ViewRoot

    ViewRoot可能比较陌生,但是其作用非常重大。所有View的绘制以及事件分发等交互都是通过它来执行或传递的。

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

    ViewRoot并不属于View树的一份子。从源码实现上来看,它既非View的子类,也非View的父类,但是,它实现了ViewParent接口,这让它可以作为View的名义上的父视图。RootView继承了Handler类,可以接收事件并分发,Android的所有触屏事件、按键事件、界面刷新等事件都是通过ViewRoot进行分发的。

    下面结构图可以清晰的揭示四者之间的关系:

    img

    二、DecorView的创建

    这部分内容主要讲DecorView是怎么一层层嵌套在Actvity,PhoneWindow中的,以及DecorView如何加载内部布局。

    setContentView

    先是从Activity中的setContentView()开始。

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

    可以看到实际是交给Window装载视图。下面来看看Activity是怎么获得Window对象的?

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

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

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

    看了下来,可能有一个疑惑:mContentParent到底是什么? 就是前面布局中@android:id/content所对应的FrameLayout。

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

    下面具体来看看installDecor();方法,怎么创建的DecroView,并设置其整体布局?

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

    再来看看 generateDecor()

    1. protected DecorView generateDecor() {
    2. return new DecorView(getContext(), -1);
    3. }

    很简单,创建了一个DecorView。

    再看generateLayout

    1. protected ViewGroup generateLayout(DecorView decor) {
    2. // 从主题文件中获取样式信息
    3. TypedArray a = getWindowStyle();
    4. ...................
    5. if (a.getBoolean(R.styleable.Window_windowNoTitle, false)) {
    6. requestFeature(FEATURE_NO_TITLE);
    7. } else if (a.getBoolean(R.styleable.Window_windowActionBar, false)) {
    8. // Don't allow an action bar if there is no title.
    9. requestFeature(FEATURE_ACTION_BAR);
    10. }
    11. ................
    12. // 根据主题样式,加载窗口布局
    13. int layoutResource;
    14. int features = getLocalFeatures();
    15. // System.out.println("Features: 0x" + Integer.toHexString(features));
    16. if ((features & (1 << FEATURE_SWIPE_TO_DISMISS)) != 0) {
    17. layoutResource = R.layout.screen_swipe_dismiss;
    18. } else if(...){
    19. ...
    20. }
    21. View in = mLayoutInflater.inflate(layoutResource, null);//加载layoutResource
    22. //往DecorView中添加子View,即文章开头介绍DecorView时提到的布局格式,那只是一个例子,根据主题样式不同,加载不同的布局。
    23. decor.addView(in, new ViewGroup.LayoutParams(MATCH_PARENT, MATCH_PARENT));
    24. mContentRoot = (ViewGroup) in;
    25. ViewGroup contentParent = (ViewGroup)findViewById(ID_ANDROID_CONTENT);// 这里获取的就是mContentParent
    26. if (contentParent == null) {
    27. throw new RuntimeException("Window couldn't find content container view");
    28. }
    29. if ((features & (1 << FEATURE_INDETERMINATE_PROGRESS)) != 0) {
    30. ProgressBar progress = getCircularProgressBar(false);
    31. if (progress != null) {
    32. progress.setIndeterminate(true);
    33. }
    34. }
    35. if ((features & (1 << FEATURE_SWIPE_TO_DISMISS)) != 0) {
    36. registerSwipeCallbacks();
    37. }
    38. // Remaining setup -- of background and title -- that only applies
    39. // to top-level windows.
    40. ...
    41. return contentParent;
    42. }

    虽然比较复杂,但是逻辑还是很清楚的。先从主题中获取样式,然后根据样式,加载对应的布局到DecorView中,然后从中获取mContentParent。获得到之后,可以回到上面的代码,为mContentParent添加View,即Activity中的布局。

    以上就是DecorView的创建过程,其实到installDecor()就已经介绍完了,后面只是具体介绍其中的逻辑。

    三、DecorView的显示

    以上仅仅是将DecorView建立起来。通过setContentView()设置的界面,为什么在onResume()之后才对用户可见呢?

    这就要从ActivityThread开始说起。

    1. private void handleLaunchActivity(ActivityClientRecord r, Intent customIntent) {
    2. //就是在这里调用了Activity.attach()呀,接着调用了Activity.onCreate()和Activity.onStart()生命周期,
    3. //但是由于只是初始化了mDecor,添加了布局文件,还没有把
    4. //mDecor添加到负责UI显示的PhoneWindow中,所以这时候对用户来说,是不可见的
    5. Activity a = performLaunchActivity(r, customIntent);
    6. ......
    7. if (a != null) {
    8. //这里面执行了Activity.onResume()
    9. handleResumeActivity(r.token, false, r.isForward,
    10. !r.activity.mFinished && !r.startsNotResumed);
    11. if (!r.activity.mFinished && r.startsNotResumed) {
    12. try {
    13. r.activity.mCalled = false;
    14. //执行Activity.onPause()
    15. mInstrumentation.callActivityOnPause(r.activity);
    16. }
    17. }
    18. }
    19. }

    重点看下handleResumeActivity(),在这其中,DecorView将会显示出来,同时重要的一个角色:ViewRoot也将登场。

    1. final void handleResumeActivity(IBinder token, boolean clearHide,
    2. boolean isForward, boolean reallyResume) {
    3. //这个时候,Activity.onResume()已经调用了,但是现在界面还是不可见的
    4. ActivityClientRecord r = performResumeActivity(token, clearHide);
    5. if (r != null) {
    6. final Activity a = r.activity;
    7. if (r.window == null && !a.mFinished && willBeVisible) {
    8. r.window = r.activity.getWindow();
    9. View decor = r.window.getDecorView();
    10. //decor对用户不可见
    11. decor.setVisibility(View.INVISIBLE);
    12. ViewManager wm = a.getWindowManager();
    13. WindowManager.LayoutParams l = r.window.getAttributes();
    14. a.mDecor = decor;
    15. l.type = WindowManager.LayoutParams.TYPE_BASE_APPLICATION;
    16. if (a.mVisibleFromClient) {
    17. a.mWindowAdded = true;
    18. //被添加进WindowManager了,但是这个时候,还是不可见的
    19. wm.addView(decor, l);
    20. }
    21. if (!r.activity.mFinished && willBeVisible
    22. && r.activity.mDecor != null && !r.hideForNow) {
    23. //在这里,执行了重要的操作,使得DecorView可见
    24. if (r.activity.mVisibleFromClient) {
    25. r.activity.makeVisible();
    26. }
    27. }
    28. }
    29. }
    30. }

    当我们执行了Activity.makeVisible()方法之后,界面才对我们是可见的。

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

    到此DecorView便可见,显示在屏幕中。但是在这其中,wm.addView(mDecor, getWindow().getAttributes());起到了重要的作用,因为其内部创建了一个ViewRootImpl对象,负责绘制显示各个子View。

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

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

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

    1. public void addView(View view, ViewGroup.LayoutParams params,
    2. Display display, Window parentWindow) {
    3. final WindowManager.LayoutParams wparams = (WindowManager.LayoutParams) params;
    4. ......
    5. synchronized (mLock) {
    6. ViewRootImpl root;
    7. //实例化一个ViewRootImpl对象
    8. root = new ViewRootImpl(view.getContext(), display);
    9. view.setLayoutParams(wparams);
    10. mViews.add(view);
    11. mRoots.add(root);
    12. mParams.add(wparams);
    13. }
    14. ......
    15. try {
    16. //将DecorView交给ViewRootImpl
    17. root.setView(view, wparams, panelParentView);
    18. } catch (RuntimeException e) {
    19. }
    20. }

    看到其中实例化了ViewRootImpl对象,然后调用其setView()方法。其中setView()方法经过一些列折腾,最终调用了performTraversals()方法,然后依照下图流程层层调用,完成绘制,最终界面才显示出来。

    img

    其实ViewRootImpl的作用不止如此,还有许多功能,如事件分发。

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

    硬件 -> ViewRootImpl -> DecorView -> PhoneWindow -> Activity

    不详细介绍了,如果感兴趣,可以看这篇文章。

    由此可见ViewRootImpl的重要性,是个连接器,负责WindowManagerService与DecorView之间的通信。

    四、总结

    以上通过源码形式介绍了Window、Activity、DecorView以及ViewRoot之间的错综关系,以及如何创建并显示DecorView。

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