本文的合集已經編著成書,高級Android開發強化實戰,歡迎各位讀友的建議和指導。在京東即可購買:https://item.jd.com/12385680.html
在View的工作過程中, 執行三大流程完成顯示, 測量(measure)流程, 布局(layout)流程, 繪制(draw)流程. 從performTraversals
方法開始, 測量(measure)View的高度(Height)與寬度(Width), 布局(layout)View在父容器中的位置, 繪制(draw)View在屏幕上.
通過源碼, 循序漸進, 解析View的工作原理和三大流程.
ViewRoot
ViewRoot連結WindowManager與DecorView, 調用流程performTraversals
, 并依次調用performMeasure
, performLayout
, performDraw
.
Measure調用onMeasure
, Layout調用onLayout
, Draw調用onDraw
與dispatchDraw
. Measure中, 調用getMeasuredHeight
與getMeasuredWidth
獲取繪制好的高度與寬度; Layout中, 調用getHeight
與getWidth
獲取布局好的高度與寬度. 注意因時機不同, Measure的度量可能不同于Layout的度量.
Measure與Layout使用onMeasure與onLayout遍歷調用子View的方法. Draw使用onDraw繪制View本身, 使用onDispatch繪制子View.
DecorView
DecorView是頂層View, 即FrameLayout, 其中包含豎直方向的LinearLayout, 標題titlebar, 內容android.R.id.content. 獲取setContentView
的布局的方法.
ViewGroup content = (ViewGroup) findViewById(android.R.id.content); // 父布局
View view = content.getChildAt(0); // 內容布局
MeasureSpec
View的MeasureSpec, MeasureSpec是32位int值, 高2位是SpecMode, 低30位是SpecSize, 選擇測量的模式, 設置測量的大小.
SpecMode三種類型, UNSPECIFIED不做任何限制; EXACTLY精確大小, 即match_parent和具體數值; AT_MOST不能超過最大距離, 即wrap_content.
在onMeasure中, View使用MeasureSpec測量View的大小, 由父布局的MeasureSpec與自身的LayoutParams決定; DecorView是根View, 由系統的窗口尺寸與自身的LayoutParams決定.
父View負責繪制子View, 子View的大小由父View的模式與大小與自身的模式與大小決定. 簡而言之, 父容器的MeasureSpec與子View的LayoutParams決定子View的MeasureSpec.
Measure
Measure測量View的高度與寬度. View調用onMeasure完成測量; ViewGroup遍歷子View的onMeasure, 再遞歸匯總.
View
View的measure
方法是禁止繼承的, 調用onMeasure
方法, 自定義View通過onMeasure
方法設置測量大小. onMeasure
方法調用setMeasuredDimension
設置測量大小.
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
setMeasuredDimension(getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec),
getDefaultSize(getSuggestedMinimumHeight(), heightMeasureSpec));
}
寬與高使用getDefaultSize
獲取默認值, 參數是推薦最小值(getSuggestedMinimumX)與指定測量規格(xMeasureSpec).
public static int getDefaultSize(int size, int measureSpec) {
int result = size;
int specMode = MeasureSpec.getMode(measureSpec);
int specSize = MeasureSpec.getSize(measureSpec);
switch (specMode) {
case MeasureSpec.UNSPECIFIED:
result = size;
break;
case MeasureSpec.AT_MOST:
case MeasureSpec.EXACTLY:
result = specSize;
break;
}
return result;
}
注意AT_MOST模式, 使用最小寬度, 當未設置時, 使用父容器的最大值, 因此自定義View需要設置默認值, 否者wrap_content
與match_parent
功能相同.
參考ViewGroup. 當子View的布局參數是WRAP_CONTENT時, 無論父View的類型, 都是父View的空閑值.
public static int getChildMeasureSpec(int spec, int padding, int childDimension) {
int specMode = MeasureSpec.getMode(spec);
int specSize = MeasureSpec.getSize(spec);
int size = Math.max(0, specSize - padding); // 最大空閑值
int resultSize = 0;
int resultMode = 0;
switch (specMode) {
// Parent has imposed an exact size on us
case MeasureSpec.EXACTLY:
// ...
} else if (childDimension == LayoutParams.WRAP_CONTENT) {
// Child wants to determine its own size. It can't be
// bigger than us.
resultSize = size; // 父View空閑寬度
resultMode = MeasureSpec.AT_MOST;
}
break;
// Parent has imposed a maximum size on us
case MeasureSpec.AT_MOST:
// ...
} else if (childDimension == LayoutParams.WRAP_CONTENT) {
// Child wants to determine its own size. It can't be
// bigger than us.
resultSize = size; // 父View空閑寬度
resultMode = MeasureSpec.AT_MOST;
}
break;
// ...
}
return MeasureSpec.makeMeasureSpec(resultSize, resultMode);
}
自定義View需要設置wrap_content
狀態下的測量值, 可以參考TextView與ImageView.
private int mMinWidth = 256; // 指定默認最小寬度
private int mMinHeight = 256; // 指定默認最小高度
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
int widthSpecMode = MeasureSpec.getMode(widthMeasureSpec);
int widthSpecSize = MeasureSpec.getSize(widthMeasureSpec);
int heightSpecMode = MeasureSpec.getMode(heightMeasureSpec);
int heightSpecSize = MeasureSpec.getSize(heightMeasureSpec);
if (widthSpecMode == MeasureSpec.AT_MOST
&& heightSpecMode == MeasureSpec.AT_MOST) {
setMeasuredDimension(mMinWidth, mMinHeight);
} else if (widthSpecMode == MeasureSpec.AT_MOST) {
setMeasuredDimension(mMinWidth, heightSpecSize);
} else if (heightSpecMode == MeasureSpec.AT_MOST) {
setMeasuredDimension(widthSpecSize, mMinHeight);
}
}
獲取建議的最小寬度, 在已設置最小寬度android:minWidth
與背景android:background
的最小寬度的最大值, 默認返回0.
protected int getSuggestedMinimumWidth() {
return (mBackground == null) ? mMinWidth : max(mMinWidth, mBackground.getMinimumWidth());
}
ViewGroup
ViewGroup使用onMeasure
繪制自己, 并遍歷子View的onMeasure遞歸繪制.
使用measureChildren
方法繪制全部子View.
protected void measureChildren(int widthMeasureSpec, int heightMeasureSpec) {
final int size = mChildrenCount;
final View[] children = mChildren;
for (int i = 0; i < size; ++i) {
final View child = children[i];
if ((child.mViewFlags & VISIBILITY_MASK) != GONE) {
measureChild(child, widthMeasureSpec, heightMeasureSpec);
}
}
}
子View繪制使用measureChild
, 最終匯總.
protected void measureChildWithMargins(View child,
int parentWidthMeasureSpec, int widthUsed,
int parentHeightMeasureSpec, int heightUsed) {
final MarginLayoutParams lp = (MarginLayoutParams) child.getLayoutParams();
final int childWidthMeasureSpec = getChildMeasureSpec(parentWidthMeasureSpec,
mPaddingLeft + mPaddingRight + lp.leftMargin + lp.rightMargin
+ widthUsed, lp.width);
final int childHeightMeasureSpec = getChildMeasureSpec(parentHeightMeasureSpec,
mPaddingTop + mPaddingBottom + lp.topMargin + lp.bottomMargin
+ heightUsed, lp.height);
child.measure(childWidthMeasureSpec, childHeightMeasureSpec);
}
不同的ViewGroup實現不同的onMeasure方法, 如LinearLayout, RelativeLayout, FrameLayout等.
測量值
View的onMeasure與Activity的生命周期不一致, 無法在生命周期的方法中, 獲取測量值. 測量值需要在測量完成后計算.
onWindowFocusChanged方法, 在Activity窗口獲得或失去焦點時都會被調用, 即在onResume與onPause執行時會調用, 此時, View的測量(Measure)已經完成, 獲取測量值.
private int mWidth; // 寬度
private int mHeight; // 高度
/**
* 在Activity獲得焦點時, 獲取測量寬度與高度
*
* @param hasFocus 關注
*/
@Override public void onWindowFocusChanged(boolean hasFocus) {
super.onWindowFocusChanged(hasFocus);
if (hasFocus) {
mWidth = getContentView().getMeasuredWidth();
mHeight = getContentView().getMeasuredHeight();
}
}
/**
* 獲取Activity的ContentView
*
* @return ContentView
*/
private View getContentView() {
ViewGroup view = (ViewGroup) getWindow().getDecorView();
FrameLayout content = (FrameLayout) view.getChildAt(0);
return content.getChildAt(0);
}
在View的消息隊列尾部, 獲取測量值. View的測量過程是在消息隊列中完成的, 完成全部的系統消息, 才會執行用戶消息.
private int mWidth; // 寬度
private int mHeight; // 高度
@Override protected void onResume() {
super.onResume();
final View view = getContentView();
view.post(new Runnable() {
@Override public void run() {
mWidth = view.getMeasuredWidth();
mHeight = view.getMeasuredHeight();
}
});
}
Layout
View使用layout
確定位置, layout調用onLayout
, 在onLayout中調用子View的layout.
layout先調用setFrame確定View的四個頂點, 即left, right, top, bottom, 再調用onLayout確定子View的位置. 在onLayout中, 調用setChildFrame確定子View的四個頂點, 子View再調用layout.
在一般情況下, View的測量(Measure)寬高與布局(Layout)寬高是相同的, 確定時機不同, 測量要早于布局.
如果在View的layout中, 重新設置寬高, 則測量寬高與布局不同, 不過此類方法, 并無任何意義.
@Override public void layout(int l, int t, int r, int b) {
super.layout(l, t, r + 256, b + 256); // 右側底部, 各加256, 無意義
}
Draw
View的繪制(Draw)過程, 首先繪制背景, 即android:backgroud
; 其次繪制自己, 即onDraw
; 再次繪制子View, 即dispatchDraw
; 最后繪制頁面裝飾, 如滾動條.
public void draw(Canvas canvas) {
// ...
/*
* Draw traversal performs several drawing steps which must be executed
* in the appropriate order:
*
* 1. Draw the background
* 2. If necessary, save the canvas' layers to prepare for fading
* 3. Draw view's content
* 4. Draw children
* 5. If necessary, draw the fading edges and restore layers
* 6. Draw decorations (scrollbars for instance)
*/
// Step 1, draw the background, if needed
int saveCount;
// 第一步, 繪制背景
if (!dirtyOpaque) {
drawBackground(canvas);
}
// skip step 2 & 5 if possible (common case)
final int viewFlags = mViewFlags;
boolean horizontalEdges = (viewFlags & FADING_EDGE_HORIZONTAL) != 0;
boolean verticalEdges = (viewFlags & FADING_EDGE_VERTICAL) != 0;
if (!verticalEdges && !horizontalEdges) {
// Step 3, draw the content
// 第二步, 繪制自己的內容
if (!dirtyOpaque) onDraw(canvas);
// Step 4, draw the children
// 第三步, 繪制子View
dispatchDraw(canvas);
// Step 6, draw decorations (scrollbars)
// 第四步, 繪制裝飾
onDrawScrollBars(canvas);
if (mOverlay != null && !mOverlay.isEmpty()) {
mOverlay.getOverlayView().dispatchDraw(canvas);
}
// we're done...
return;
}
// ...
}
關注源碼的繪制
draw
流程: drawBackground -> onDraw -> dispatchDraw -> onDrawScrollBars
View的工作原理來源于三大流程, 測量(measure)流程, 布局(layout)流程, 繪制(draw)流程. 通過源碼理解View的三大流程, 有利于提升程序設計理念, 與開發質量.
That's all! Enjoy it!