Android 中 View 繪製流程分析

robert_chao發表於2016-07-22

建立Window

在Activity的attach方法中通過呼叫PolicyManager.makeNewWindo建立Window,將一個View add到WindowManager時,WindowManagerImpl建立一個ViewRoot來管理該視窗的根View。並通過ViewRoot.setView方法把該View傳給ViewRoot。

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) {  
    attachBaseContext(context);  

    mFragments.attachActivity(this, mContainer, null);  

    mWindow = PolicyManager.makeNewWindow(this);  
    mWindow.setCallback(this);  
    mWindow.getLayoutInflater().setPrivateFactory(this);

建立DecorView

DecorView為整個Window介面的最頂層View。

Activity中的Window物件幫我們建立了一個PhoneWindow內部類DecorView(父類為FrameLayout)視窗頂層檢視,然後通過LayoutInflater將xml內容佈局解析成View樹形結構新增到DecorView頂層檢視中id為content的FrameLayout父容器上面。Activity的content內容佈局最終會新增到DecorView視窗頂層檢視上面。

protected boolean initializePanelDecor(PanelFeatureState st) {  
    st.decorView = new DecorView(getContext(), st.featureId);  
    st.gravity = Gravity.CENTER | Gravity.BOTTOM;  
    st.setStyle(getContext());  

    return true;  
}

建立ViewRoot並關聯View

WindowManagerImpl儲存DecorView到mViews,建立對應的ViewRoot;

ViewRoot用於管理視窗的根View,並和global window manger進行互動。ViewRoot中有一個nested class: W,W是一個Binder子類,用於接收global window manager的各種訊息, 如按鍵訊息, 觸控訊息等。 ViewRoot有一個W型別的成員mWindow,ViewRoot在Constructor中建立一個W的instance並賦值給mWindow。 ViewRoot是Handler的子類, W會通過Looper把訊息傳遞給ViewRoot。 ViewRoot在setView方法中把mWindow傳給sWindowSession。

public void addView(View view, ViewGroup.LayoutParams params,  
        Display display, Window parentWindow) {  
    if (view == null) {  
        throw new IllegalArgumentException("view must not be null");  
    }  
    if (display == null) {  
        throw new IllegalArgumentException("display must not be null");  
    }  
    if (!(params instanceof WindowManager.LayoutParams)) {  
        throw new IllegalArgumentException("Params must be WindowManager.LayoutParams");  
    }  

    final WindowManager.LayoutParams wparams = (WindowManager.LayoutParams)params;  
    if (parentWindow != null) {  
        parentWindow.adjustLayoutParamsForSubWindow(wparams);  
    }  

    ViewRootImpl root;  
    View panelParentView = null;  

    synchronized (mLock) {  
        // Start watching for system property changes.  
        if (mSystemPropertyUpdater == null) {  
            mSystemPropertyUpdater = new Runnable() {  
                @Override public void run() {  
                    synchronized (mLock) {  
                        for (ViewRootImpl viewRoot : mRoots) {  
                            viewRoot.loadSystemProperties();  
                        }  
                    }  
                }  
            };  
            SystemProperties.addChangeCallback(mSystemPropertyUpdater);  
        }  

        int index = findViewLocked(view, false);  
        if (index >= 0) {  
            throw new IllegalStateException("View " + view  
                    + " has already been added to the window manager.");  
        }  

        // If this is a panel window, then find the window it is being  
        // attached to for future reference.  
        if (wparams.type >= WindowManager.LayoutParams.FIRST_SUB_WINDOW &&  
                wparams.type <= WindowManager.LayoutParams.LAST_SUB_WINDOW) {  
            final int count = mViews != null ? mViews.length : 0;  
            for (int i=0; i<count; i++) {  
                if (mRoots[i].mWindow.asBinder() == wparams.token) {  
                    panelParentView = mViews[i];  
                }  
            }  
        }  

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

        view.setLayoutParams(wparams);  

        if (mViews == null) {  
            index = 1;  
            mViews = new View[1];  
            mRoots = new ViewRootImpl[1];  
            mParams = new WindowManager.LayoutParams[1];  
        } else {  
            index = mViews.length + 1;  
            Object[] old = mViews;  
            mViews = new View[index];  
            System.arraycopy(old, 0, mViews, 0, index-1);  
            old = mRoots;  
            mRoots = new ViewRootImpl[index];  
            System.arraycopy(old, 0, mRoots, 0, index-1);  
            old = mParams;  
            mParams = new WindowManager.LayoutParams[index];  
            System.arraycopy(old, 0, mParams, 0, index-1);  
        }  
        index--;  

        mViews[index] = view;  
        mRoots[index] = root;  
        mParams[index] = wparams;  
    }  

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

ViewRoot是GUI管理系統與GUI呈現系統之間的橋樑,需要注意它並不是一個View型別。

它的主要作用如下:

1、向DecorView分發收到的使用者發起的event事件,如按鍵,觸屏,軌跡球等事件;
2、與WindowManagerService互動,完成整個Activity的GUI的繪製。

View繪製基本流程

這裡先給出Android系統View的繪製流程:依次執行View類裡面的如下三個方法:

measure(int ,int) :測量View的大小
layout(int ,int ,int ,int) :設定子View的位置
draw(Canvas) :繪製View內容到Canvas畫布上

整個View樹的繪圖流程是在ViewRoot.Java類的performTraversals()函式展開的,該函式做的執行過程可簡單概況為根據之前設定的狀態,判斷是否需要重新計算檢視大小(measure)、是否重新需要安置檢視的位置(layout)、以及是否需要重繪 (draw)

 mesarue()測量過程

主要作用:為整個View樹計算實際的大小,即設定實際的高(mMeasuredHeight)和寬(mMeasureWidth),每個View的控制元件的實際寬高都是由父檢視和本身檢視決定的。

具體的呼叫如下:

ViewRootImpl 的performTraversals方法中,呼叫measureHierarchy,然後呼叫performMeasure

private void performMeasure(int childWidthMeasureSpec, int childHeightMeasureSpec) {  
       Trace.traceBegin(Trace.TRACE_TAG_VIEW, "measure");  
       try {  
           mView.measure(childWidthMeasureSpec, childHeightMeasureSpec);  
       } finally {  
           Trace.traceEnd(Trace.TRACE_TAG_VIEW);  
       }  
   }

ViewRoot根物件地屬性mView(其型別一般為ViewGroup型別)呼叫measure()方法去計算View樹的大小,回撥View/ViewGroup物件的onMeasure()方法,該方法實現的功能如下:

1、設定本View檢視的最終大小,該功能的實現通過呼叫setMeasuredDimension()方法去設定實際的高(mMeasuredHeight)和寬(mMeasureWidth)

2、如果該View物件是個ViewGroup型別,需要重寫onMeasure()方法,對其子檢視進行遍歷的measure()過程。

對每個子檢視的measure()過程,是通過呼叫父類ViewGroup.java類裡的measureChildWithMargins()方法去實現,該方法內部只是簡單地呼叫了View物件的measure()方法。

整個measure呼叫流程就是個樹形的遞迴過程measure()方法兩個引數都是父View傳遞過來的,也就是代表了父view的規格。他由兩部分組成,高2位表示MODE,定義在MeasureSpec類(View的內部類)中,有三種型別,MeasureSpec.EXACTLY表示確定大小, MeasureSpec.AT_MOST表示最大大小, MeasureSpec.UNSPECIFIED不確定。低30位表示size,也就是父View的大小。對於系統Window類的DecorVIew物件Mode一般都為MeasureSpec.EXACTLY ,而size分別對應螢幕寬高。對於子View來說大小是由父View和子View共同決定的。

protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {  
    setMeasuredDimension(getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec),  
            getDefaultSize(getSuggestedMinimumHeight(), heightMeasureSpec));  
}
protected final void setMeasuredDimension(int measuredWidth, int measuredHeight) {  
     boolean optical = isLayoutModeOptical(this);  
     if (optical != isLayoutModeOptical(mParent)) {  
         Insets insets = getOpticalInsets();  
         int opticalWidth  = insets.left + insets.right;  
         int opticalHeight = insets.top  + insets.bottom;  

         measuredWidth  += optical ? opticalWidth  : -opticalWidth;  
         measuredHeight += optical ? opticalHeight : -opticalHeight;  
     }  
     mMeasuredWidth = measuredWidth;  
     mMeasuredHeight = measuredHeight;  

     mPrivateFlags |= PFLAG_MEASURED_DIMENSION_SET;  
 }

layout佈局過程

主要作用 :為將整個根據子檢視的大小以及佈局引數將View樹放到合適的位置上。

具體的呼叫如下:

ViewRootImpl 的performTraversals方法中,呼叫performLayout

private void performLayout(WindowManager.LayoutParams lp, int desiredWindowWidth,  
        int desiredWindowHeight) {  
    mLayoutRequested = false;  
    mScrollMayChange = true;  
    mInLayout = true;  

    final View host = mView;  
    if (DEBUG_ORIENTATION || DEBUG_LAYOUT) {  
        Log.v(TAG, "Laying out " + host + " to (" +  
                host.getMeasuredWidth() + ", " + host.getMeasuredHeight() + ")");  
    }  

    Trace.traceBegin(Trace.TRACE_TAG_VIEW, "layout");  
    try {  
        host.layout(0, 0, host.getMeasuredWidth(), host.getMeasuredHeight());  

        mInLayout = false;  
        int numViewsRequestingLayout = mLayoutRequesters.size();  
        if (numViewsRequestingLayout > 0) {  
            // requestLayout() was called during layout.  
            // If no layout-request flags are set on the requesting views, there is no problem.  
            // If some requests are still pending, then we need to clear those flags and do  
            // a full request/measure/layout pass to handle this situation.  
            ArrayList<View> validLayoutRequesters = getValidLayoutRequesters(mLayoutRequesters,  
                    false);  
            if (validLayoutRequesters != null) {  
                // Set this flag to indicate that any further requests are happening during  
                // the second pass, which may result in posting those requests to the next  
                // frame instead  
                mHandlingLayoutInLayoutRequest = true;  

                // Process fresh layout requests, then measure and layout  
                int numValidRequests = validLayoutRequesters.size();  
                for (int i = 0; i < numValidRequests; ++i) {  
                    final View view = validLayoutRequesters.get(i);  
                    Log.w("View", "requestLayout() improperly called by " + view +  
                            " during layout: running second layout pass");  
                    view.requestLayout();  
                }  
                measureHierarchy(host, lp, mView.getContext().getResources(),  
                        desiredWindowWidth, desiredWindowHeight);  
                mInLayout = true;  
                host.layout(0, 0, host.getMeasuredWidth(), host.getMeasuredHeight());  

                mHandlingLayoutInLayoutRequest = false;  

                // Check the valid requests again, this time without checking/clearing the  
                // layout flags, since requests happening during the second pass get noop'd  
                validLayoutRequesters = getValidLayoutRequesters(mLayoutRequesters, true);  
                if (validLayoutRequesters != null) {  
                    final ArrayList<View> finalRequesters = validLayoutRequesters;  
                    // Post second-pass requests to the next frame  
                    getRunQueue().post(new Runnable() {  
                        @Override  
                        public void run() {  
                            int numValidRequests = finalRequesters.size();  
                            for (int i = 0; i < numValidRequests; ++i) {  
                                final View view = finalRequesters.get(i);  
                                Log.w("View", "requestLayout() improperly called by " + view +  
                                        " during second layout pass: posting in next frame");  
                                view.requestLayout();  
                            }  
                        }  
                    });  
                }  
            }  

        }  
    } finally {  
        Trace.traceEnd(Trace.TRACE_TAG_VIEW);  
    }  
    mInLayout = false;  
}

host.layout()開始View樹的佈局,繼而回撥給View/ViewGroup類中的layout()方法。具體流程如下

1 、layout方法會設定該View檢視位於父檢視的座標軸,即mLeft,mTop,mLeft,mBottom(呼叫setFrame()函式去實現),接下來回撥onLayout()方法(如果該View是ViewGroup物件,需要實現該方法,對每個子檢視進行佈局)。

2、如果該View是個ViewGroup型別,需要遍歷每個子檢視chiildView,呼叫該子檢視的layout()方法去設定它的座標值。

protected void onLayout(boolean changed, int left, int top, int right, int bottom) {  
}
public void layout(int l, int t, int r, int b) {  
    int oldL = mLeft;  
    int oldT = mTop;  
    int oldB = mBottom;  
    int oldR = mRight;  
    boolean changed = isLayoutModeOptical(mParent) ?  
            setOpticalFrame(l, t, r, b) : setFrame(l, t, r, b);  
    if (changed || (mPrivateFlags & PFLAG_LAYOUT_REQUIRED) == PFLAG_LAYOUT_REQUIRED) {  
        onLayout(changed, l, t, r, b);  
        mPrivateFlags &= ~PFLAG_LAYOUT_REQUIRED;  

        ListenerInfo li = mListenerInfo;  
        if (li != null && li.mOnLayoutChangeListeners != null) {  
            ArrayList<OnLayoutChangeListener> listenersCopy =  
                    (ArrayList<OnLayoutChangeListener>)li.mOnLayoutChangeListeners.clone();  
            int numListeners = listenersCopy.size();  
            for (int i = 0; i < numListeners; ++i) {  
                listenersCopy.get(i).onLayoutChange(this, l, t, r, b, oldL, oldT, oldR, oldB);  
            }  
        }  
    }  
    mPrivateFlags &= ~PFLAG_FORCE_LAYOUT;  
}

draw()繪圖過程

ViewRootImpl 的performTraversals方法中,呼叫了mView的draw方法

mView.draw()開始繪製,draw()方法實現的功能如下:

1 、繪製該View的背景
2 、為顯示漸變框做一些準備操作
3、呼叫onDraw()方法繪製檢視本身   (每個View都需要過載該方法,ViewGroup不需要實現該方法)
4、呼叫dispatchDraw ()方法繪製子檢視(如果該View型別不為ViewGroup,即不包含子檢視,不需要過載該方法)

值得說明的是,ViewGroup類已經為我們重寫了dispatchDraw ()的功能實現,應用程式一般不需要重寫該方法,但可以過載父類函式實現具體的功能。

dispatchDraw()方法內部會遍歷每個子檢視,呼叫drawChild()去重新回撥每個子檢視的draw()方法。

5、繪製滾動條

重新整理檢視

Android中實現view的更新有兩個方法,一個是invalidate,另一個是postInvalidate,其中前者是在UI執行緒自身中使用,而後者在非UI執行緒中使用。

requestLayout()方法 :會導致呼叫measure()過程 和 layout()過程 。

說明:只是對View樹重新佈局layout過程包括measure()和layout()過程,不會呼叫draw()過程,但不會重新繪製
任何檢視包括該呼叫者本身。
一般引起invalidate()操作的函式如下:

1、直接呼叫invalidate()方法,請求重新draw(),但只會繪製呼叫者本身。

2、setSelection()方法 :請求重新draw(),但只會繪製呼叫者本身。

3、setVisibility()方法 : 當View可視狀態在INVISIBLE轉換VISIBLE時,會間接呼叫invalidate()方法,繼而繪製該View。

4 、setEnabled()方法 : 請求重新draw(),但不會重新繪製任何檢視包括該呼叫者本身。

內容參考原始碼,借鑑了網上的一些分析。

相關文章