您好,登錄后才能下訂單哦!
這篇文章主要介紹了Android中View繪制流程的示例分析,具有一定借鑒價值,感興趣的朋友可以參考下,希望大家閱讀完這篇文章之后大有收獲,下面讓小編帶著大家一起了解一下。
創建Window
Window即窗口,這個概念在AndroidFramework中的實現為android.view.Window這個抽象類,這個抽象類是對Android系統中的窗口的抽象。在介紹這個類之前,我們先來看看究竟什么是窗口呢?
實際上,窗口是一個宏觀的思想,它是屏幕上用于繪制各種UI元素及響應用戶輸入事件的一個矩形區域。通常具備以下兩個特點:
獨立繪制,不與其它界面相互影響;
不會觸發其它界面的輸入事件;
在Android系統中,窗口是獨占一個Surface實例的顯示區域,每個窗口的Surface由WindowManagerService分配。我們可以把Surface看作一塊畫布,應用可以通過Canvas或OpenGL在其上面作畫。畫好之后,通過SurfaceFlinger將多塊Surface按照特定的順序(即Z-order)進行混合,而后輸出到FrameBuffer中,這樣用戶界面就得以顯示。
android.view.Window這個抽象類可以看做Android中對窗口這一宏觀概念所做的約定,而PhoneWindow這個類是Framework為我們提供的Android窗口概念的具體實現。接下來我們先來介紹一下android.view.Window這個抽象類。
這個抽象類包含了三個核心組件:
WindowManager.LayoutParams:窗口的布局參數;
Callback:窗口的回調接口,通常由Activity實現;
ViewTree:窗口所承載的控件樹。
在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(),但不會重新繪制任何視圖包括該調用者本身。
Android是一種基于Linux內核的自由及開放源代碼的操作系統,主要使用于移動設備,如智能手機和平板電腦,由美國Google公司和開放手機聯盟領導及開發。
感謝你能夠認真閱讀完這篇文章,希望小編分享的“Android中View繪制流程的示例分析”這篇文章對大家有幫助,同時也希望大家多多支持億速云,關注億速云行業資訊頻道,更多相關知識等著你來學習!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。