Activity,Window,DecorView,ViewRoot,View的關(guān)系

簡介

  • Activity是一個(gè)工人,它來控制Window;Window是一面顯示屏,用來顯示信息;View就是要顯示在顯示屏上的信息,這些View都是層層重疊在一起(通過infalte()和addView())放到Window顯示屏上的。而LayoutInfalter就是用來生成View的一個(gè)工具,XML布局文件就是用來生成View的原料

  • Activity并不負(fù)責(zé)視圖控制,它只是控制生命周期和處理事件,真正控制視圖的是Window。一個(gè)Activity包含了一個(gè)Window,Window才是真正代表一個(gè)窗口,Window 中持有一個(gè) DecorView,而這個(gè)DecorView才是 view 的根布局。

  • DecorView是FrameLayout的子類,它可以被認(rèn)為是Android視圖樹的根節(jié)點(diǎn)視圖。DecorView作為頂級(jí)View,一般情況下它內(nèi)部包含一個(gè)豎直方向的LinearLayout,在這個(gè)LinearLayout里面有上下兩個(gè)部分(具體情況和Android版本及主體有關(guān)),上面的是標(biāo)題欄,下面的是內(nèi)容欄。在Activity中通過setContentView所設(shè)置的布局文件其實(shí)就是被加到內(nèi)容欄之中的,而內(nèi)容欄的id是content,在代碼中可以通過ViewGroup content = (ViewGroup)findViewById(R.android.id.content)來得到content對(duì)應(yīng)的layout。

  • ViewRoot對(duì)應(yīng)ViewRootImpl類,它是連接WindowManagerService和DecorView的紐帶,View的三大流程(測量(measure),布局(layout),繪制(draw))均通過ViewRoot來完成。ViewRoot并不屬于View樹的一份子。從源碼實(shí)現(xiàn)上來看,它既非View的子類,也非View的父類,但是,它實(shí)現(xiàn)了ViewParent接口,這讓它可以作為View的名義上的父視圖。RootView繼承了Handler類,可以接收事件并分發(fā),Android的所有觸屏事件、按鍵事件、界面刷新等事件都是通過ViewRoot進(jìn)行分發(fā)的。ViewRoot可以被理解為“View樹的管理者”——它有一個(gè)mView成員變量,它指向的對(duì)象和上文中Window和Activity的mDecor指向的對(duì)象是同一個(gè)對(duì)象。

從 setContentView 分析起

眾所周知,在 activity 中,setContentView方法可以設(shè)置我們需要的布局,那么就從這個(gè)作為切入點(diǎn)開始分析

//activity
    public void setContentView(View view, ViewGroup.LayoutParams params) {
        getWindow().setContentView(view, params);
        initWindowDecorActionBar();
    }

    /**
     * Retrieve the current {@link android.view.Window} for the activity.
     * This can be used to directly access parts of the Window API that
     * are not available through Activity/Screen.
     *
     * @return Window The current window, or null if the activity is not
     *         visual.
     */
    public Window getWindow() {
        return mWindow;
    }

繼續(xù)尋找 mWindow 的賦值時(shí)機(jī)

 final void attach(Context context, ActivityThread aThread,
...
        mWindow = new PhoneWindow(this);
        mWindow.setCallback(this);//當(dāng)window接收系統(tǒng)發(fā)送給它的IO輸入事件時(shí),例如鍵盤和觸摸屏事件,就可以轉(zhuǎn)發(fā)給相應(yīng)的Activity
        mWindow.setOnWindowDismissedCallback(this);
        mWindow.getLayoutInflater().setPrivateFactory(this);
        if (info.softInputMode != WindowManager.LayoutParams.SOFT_INPUT_STATE_UNSPECIFIED) {
            mWindow.setSoftInputMode(info.softInputMode);
        }

可以看到在attach,實(shí)例化了一個(gè)PhoneWindow對(duì)象(window 的實(shí)現(xiàn)),繼續(xù)看 window 中 setContentView的實(shí)現(xiàn)

@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) {
       installDecor();//[window]如何沒有DecorView,那么就新建一個(gè)
   } else if (!hasFeature(FEATURE_CONTENT_TRANSITIONS)) {
       mContentParent.removeAllViews();
   }

   if (hasFeature(FEATURE_CONTENT_TRANSITIONS)) {
       final Scene newScene = Scene.getSceneForLayout(mContentParent, layoutResID,
               getContext());
       transitionTo(newScene);
   } else {
       mLayoutInflater.inflate(layoutResID, mContentParent); //[window]第二步,將layout添加到mContentParent
   }
   mContentParent.requestApplyInsets();
   final Callback cb = getCallback();
   if (cb != null && !isDestroyed()) {
       cb.onContentChanged();
   }
}

//注意 mContentParent的注釋,后續(xù)做分析
    // This is the view in which the window contents are placed. It is either
    // mDecor itself, or a child of mDecor where the contents go.
    private ViewGroup mContentParent;

創(chuàng)建DecorView

繼續(xù)看 PhoneWindow 中的installDecor() 方法

    private void installDecor() {
        if (mDecor == null) {
            mDecor = generateDecor(); //DecorView 被賦值
    mDecor.setDescendantFocusability(ViewGroup.FOCUS_AFTER_DESCENDANTS);
            mDecor.setIsRootNamespace(true);
            if (!mInvalidatePanelMenuPosted && mInvalidatePanelMenuFeatures != 0) {
                mDecor.postOnAnimation(mInvalidatePanelMenuRunnable);
            }
        }
        if (mContentParent == null) {
            mContentParent = generateLayout(mDecor);

...

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

protected ViewGroup generateLayout(DecorView decor) {
        // Apply data from current theme.
        // 從主題文件中獲取樣式信息
        TypedArray a = getWindowStyle();

        ...

        if (a.getBoolean(R.styleable.Window_windowNoTitle, false)) {
            requestFeature(FEATURE_NO_TITLE);
        } else if (a.getBoolean(R.styleable.Window_windowActionBar, false)) {
            // Don't allow an action bar if there is no title.
            requestFeature(FEATURE_ACTION_BAR);
        }

        if(...){
            ...
        }
//[window] 以上都是根據(jù)不同的style生成不同的decorview
        // 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(...){
            ...
        }

        View in = mLayoutInflater.inflate(layoutResource, null);    //加載layoutResource
        decor.addView(in, new ViewGroup.LayoutParams(MATCH_PARENT, MATCH_PARENT)); //往DecorView中添加子View,即mContentParent,// 加入到deco中,所以應(yīng)該是其第一個(gè)child
        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) {
            registerSwipeCallbacks();
        }

        // Remaining setup -- of background and title -- that only applies
        // to top-level windows.
        ...

        return contentParent;
    }

由以上代碼可以看出,該方法還是做了相當(dāng)多的工作的,首先根據(jù)設(shè)置的主題樣式來設(shè)置DecorView的風(fēng)格,比如說有沒有titlebar之類的,接著為DecorView添加子View,而這里的子View則是上面提到的mContentParent,如果上面設(shè)置了FEATURE_NO_ACTIONBAR,那么DecorView就只有mContentParent一個(gè)子View,這也解釋了上面的注釋:mContentParent是DecorView本身或者是DecorView的一個(gè)子元素。

Paste_Image.png

小結(jié):

  • DecorView是頂級(jí)View,內(nèi)部有titlebar和contentParent兩個(gè)子元素,contentParent的id是content,而我們設(shè)置的main.xml布局則是contentParent里面的一個(gè)子元素。
  • 在DecorView創(chuàng)建完畢后,讓我們回到PhoneWindow#setContentView方法,LayoutInflater.inflate(layoutResID, mContentParent);這里加載了我們設(shè)置的main.xml布局文件,并且設(shè)置mContentParent為main.xml的父布局,

到目前為止,通過setContentView方法,創(chuàng)建了DecorView和加載了我們提供的布局,但是這時(shí),我們的View還是不可見的,因?yàn)槲覀儍H僅是加載了布局,并沒有對(duì)View進(jìn)行任何的測量、布局、繪制工作。在View進(jìn)行測量流程之前,還要進(jìn)行一個(gè)步驟,那就是把DecorView添加至window中,然后經(jīng)過一系列過程觸發(fā)ViewRootImpl#performTraversals方法,在該方法內(nèi)部會(huì)正式開始測量、布局、繪制這三大流程。

將DecorView添加至Window

每一個(gè)Activity組件都有一個(gè)關(guān)聯(lián)的Window對(duì)象,用來描述一個(gè)應(yīng)用程序窗口。每一個(gè)應(yīng)用程序窗口內(nèi)部又包含有一個(gè)View對(duì)象,用來描述應(yīng)用程序窗口的視圖。上文分析了創(chuàng)建DecorView的過程,現(xiàn)在則要把DecorView添加到Window對(duì)象中。而要了解這個(gè)過程,我們要簡單先了解一下Activity的創(chuàng)建過程:
首先,在ActivityThread#handleLaunchActivity中啟動(dòng)Activity,在這里面會(huì)調(diào)用到Activity#onCreate方法,從而完成上面所述的DecorView創(chuàng)建動(dòng)作,當(dāng)onCreate()方法執(zhí)行完畢,在handleLaunchActivity方法會(huì)繼續(xù)調(diào)用到ActivityThread#handleResumeActivity方法,

final void handleResumeActivity(IBinder token, boolean clearHide, boolean isForward) { 
    //...
    ActivityClientRecord r = performResumeActivity(token, clearHide); // 這里會(huì)調(diào)用到onResume()方法

    if (r != null) {
        final Activity a = r.activity;

        //...
        if (r.window == null && !a.mFinished && willBeVisible) {
            r.window = r.activity.getWindow(); // 獲得window對(duì)象
            View decor = r.window.getDecorView(); // 獲得DecorView對(duì)象
            decor.setVisibility(View.INVISIBLE);
            ViewManager wm = a.getWindowManager(); // 獲得windowManager對(duì)象
            WindowManager.LayoutParams l = r.window.getAttributes();
            a.mDecor = decor;
            l.type = WindowManager.LayoutParams.TYPE_BASE_APPLICATION;
            l.softInputMode |= forwardBit;
            if (a.mVisibleFromClient) {
                a.mWindowAdded = true;
                wm.addView(decor, l); // 調(diào)用addView方法
            }
            //...
        }
    }
}

在該方法內(nèi)部,獲取該activity所關(guān)聯(lián)的window對(duì)象,DecorView對(duì)象,以及windowManager對(duì)象,而WindowManager是抽象類,它的實(shí)現(xiàn)類是WindowManagerImpl,所以后面調(diào)用的是WindowManagerImpl#addView方法,我們看看源碼:

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);
    }
}

接著調(diào)用了mGlobal的成員函數(shù),而mGlobal則是WindowManagerGlobal的一個(gè)實(shí)例,那么我們接著看WindowManagerGlobal#addView方法

public void addView(View view, ViewGroup.LayoutParams params,
            Display display, Window parentWindow) {
        ...

        ViewRootImpl root;
        View panelParentView = null;

        synchronized (mLock) {
            ...

            root = new ViewRootImpl(view.getContext(), display); // 1

            view.setLayoutParams(wparams);

            mViews.add(view);
            mRoots.add(root);
            mParams.add(wparams);
        }

        // do this last because it fires off messages to start doing things
        try {
            root.setView(view, wparams, panelParentView); // 2
        } catch (RuntimeException e) {
            // BadTokenException or InvalidDisplayException, clean up.
            synchronized (mLock) {
                final int index = findViewLocked(view, false);
                if (index >= 0) {
                    removeViewLocked(index, true);
                }
            }
            throw e;
        }
    }

先看①號(hào)代碼處,實(shí)例化了ViewRootImpl類,接著,在②號(hào)代碼處,調(diào)用ViewRootImpl#setView方法,并把DecorView作為參數(shù)傳遞進(jìn)去,在這個(gè)方法內(nèi)部,會(huì)通過跨進(jìn)程的方式向WMS(WindowManagerService)發(fā)起一個(gè)調(diào)用,從而將DecorView最終添加到Window上,在這個(gè)過程中,ViewRootImpl、DecorView和WMS會(huì)彼此關(guān)聯(lián),至于詳細(xì)過程這里不展開來說了。
最后通過WMS調(diào)用ViewRootImpl#performTraverals方法開始View的測量、布局、繪制流程.

參考

http://m.itdecent.cn/p/687010ccad66

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容