Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> 關於Android編程 >> Android中View繪制流程分析

Android中View繪制流程分析

編輯:關於Android編程

創建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= 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 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 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 listenersCopy =
                        (ArrayList)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(),但不會重新繪制任何視圖包括該調用者本身。

  1. 上一頁:
  2. 下一頁:
熱門文章
閱讀排行版
Copyright © Android教程網 All Rights Reserved