Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
您现在的位置: Android教程網 >> Android系統教程 >  >> Android 技術 >> Android 資訊

Android View 繪製流程源碼分析:從 Window 到 draw

編輯:Android 資訊

建立 Window

Activity 在 attach 方法中透過 PolicyManager.makeNewWindow 建立 Window。當一個 View 被加入 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 上——我們寫的 content 佈局最終都落在這裡。

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,並與全域的 WindowManagerService 互動。它內部有一個名為 W 的 nested class,是 Binder 的子類,用來接收系統視窗管理器送來的各種訊息,例如按鍵、觸摸;ViewRoot 以 mWindow 持有 W 的實例,並在 setView 中把 mWindow 交給 sWindowSession。W 收到訊息後透過 Looper 轉交給 ViewRoot——ViewRoot 本身就是 Handler 的子類。

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 並不是一種 View 類型。它是 GUI 管理系統與 GUI 呈現系統之間的橋梁,主要負責兩件事:

1、把使用者產生的 event(按鍵、觸摸、軌跡球等)分發給 DecorView;

2、與 WindowManagerService 協作,完成整個 Activity 的 GUI 繪製。

繪製的三個基本步驟

Android 的 View 繪製依序執行三個方法:

measure(int, int):測量 View 的大小

layout(int, int, int, int):決定子 View 的位置

draw(Canvas):把內容畫到 Canvas 上

整棵 View 樹的繪圖流程由 ViewRootImpl 的 performTraversals() 展開,它依先前記錄的狀態判斷是否需要重新測量、重新布局、重新繪製。

measure:算出實際尺寸

目的是為整棵 View 樹計算實際寬高,寫入 mMeasuredWidth 與 mMeasuredHeight。每個控件的尺寸由父視圖與自身共同決定。

呼叫路徑是: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); } }

根物件 mView(通常是 ViewGroup)呼叫 measure() 後會回呼 onMeasure(),它負責兩件事:

1、呼叫 setMeasuredDimension() 設定自己的最終尺寸;

2、若本身是 ViewGroup,則需覆寫 onMeasure() 並遍歷子視圖,透過 ViewGroup 的 measureChildWithMargins() 逐一測量(該方法內部只是轉呼子 View 的 measure())。

整個 measure 是一個樹狀遞歸。傳入的兩個參數代表父 View 的規格,高 2 位是 mode、低 30 位是 size。mode 定義在 MeasureSpec(View 的內部類)中,有三種:EXACTLY 表示確切尺寸、AT_MOST 表示上限、UNSPECIFIED 表示不確定。Window 的 DecorView 通常是 EXACTLY 加螢幕寬高;子 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 樹放到正確座標上。呼叫路徑是 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 會先呼叫 setFrame() 設定該 View 在父容器中的座標(mLeft、mTop、mRight、mBottom),接著回呼 onLayout();若是 ViewGroup 則需實作它以安排每個子 View。

2、ViewGroup 會遍歷每個子 View,逐一呼叫其 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:真正畫出來

performTraversals 中會呼叫 mView.draw(),它依序做五件事:

1、繪製該 View 的背景;

2、為顯示漸變框做準備;

3、呼叫 onDraw() 繪製 View 本身(每個 View 都應覆寫,ViewGroup 不需要);

4、呼叫 dispatchDraw() 繪製子視圖(非 ViewGroup 則不需要)。ViewGroup 已經為我們實作了 dispatchDraw(),一般不必覆寫,但可以在其中加入自訂邏輯。它內部會遍歷子視圖並呼叫 drawChild(),後者再回呼子 View 的 draw();

5、繪製滾動條。

刷新視圖

Android 中更新 View 有兩個方法:invalidate 用於 UI 線程自身,postInvalidate 用於非 UI 線程。

requestLayout() 會觸發 measure() 與 layout() 流程。它重新布局,但不會調用 draw(),也就是說任何視圖(包括呼叫者本身)都不會被重繪。

而以下操作通常會間接引起 invalidate():

1、直接呼叫 invalidate():請求重繪,但只畫呼叫者本身。

2、setSelection():請求重繪,同樣只畫呼叫者本身。

3、setVisibility():當可視狀態由 INVISIBLE 變為 VISIBLE 時,會間接呼叫 invalidate() 進而繪製該 View。

4、setEnabled():請求重繪,但實際上不會重畫任何視圖,包括呼叫者本身。

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

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved