View的工作原理閱讀筆記
- 初識ViewRoot和DecorView
-
- DecorView的結構
- Measure過程
-
- MeaureSpec
-
- MeaureSpec的含義
- SpecMode 的類型
- MeasureSpec 和 LayoutParams 的對應關系
- LinearLayout Measure 示例
- 擷取view寬高的時機
- layout過程
- draw過程
- 自定義view注意事項
初識ViewRoot和DecorView
ViewRoot:
聯系windowManager和Decorview的紐帶,View的三大流程均通過ViewRoot完成
DecorView:
是Activity的頂級view。内部通常包含一個LinearLayout.
在ActivityThread的ApplicationThread中,在完成activity的建立後,會調用方法handleResumeActivity,去完成onresume的調用。在handleResumeActivity方法中
final void handleResumeActivity(IBinder token,
boolean clearHide, boolean isForward, boolean reallyResume) {
//...
if (r.window == null && !a.mFinished && willBeVisible) {
r.window = r.activity.getWindow();
View decor = r.window.getDecorView();
decor.setVisibility(View.INVISIBLE);
ViewManager wm = a.getWindowManager();
WindowManager.LayoutParams l = r.window.getAttributes();
a.mDecor = decor;
l.type = WindowManager.LayoutParams.TYPE_BASE_APPLICATION;
l.softInputMode |= forwardBit;
if (a.mVisibleFromClient) {
a.mWindowAdded = true;
//将decorView添加到windowManager
wm.addView(decor, l);
}
}
//...
}
這裡的windowManager的具體實作者是WindowManagerImpl。是以我們來看WindowManagerImpl的addView。
private final WindowManagerGlobal mGlobal = WindowManagerGlobal.getInstance();
@Override
public void addView(@NonNull View view, @NonNull ViewGroup.LayoutParams params) {
applyDefaultToken(params);
mGlobal.addView(view, params, mDisplay, mParentWindow);
}
這裡調用了WindowManagerGlobal的addview
public void addView(View view, ViewGroup.LayoutParams params,
Display display, Window parentWindow) {
//...
synchronized (mLock) {
//....
//這裡就是書上的源碼了,将viewrootimpl和decorview建立關聯
root = new ViewRootImpl(view.getContext(), display);
view.setLayoutParams(wparams);
mViews.add(view);
mRoots.add(root);
mParams.add(wparams);
}
// do this last because it fires off messages to start doing things
root.setView(view, wparams, panelParentView);
//..
}
DecorView的結構
DecorView繼承自FrameLayout。一般來講内部包含一個LinearLayout。
而這個LinearLayout是在PhoneWindow初始化DecorView的時候,在generateLayout方法中添加的。
protected ViewGroup generateLayout(DecorView decor) {
int layoutResource;
int features = getLocalFeatures();
// System.out.println("Features: 0x" + Integer.toHexString(features));
if ((features & (1 << FEATURE_SWIPE_TO_DISMISS)) != 0) {
//...這裡省略了若幹判斷分支,根據主題不同加載不同的布局
} else {
// Embedded, so no decoration is needed.
//如果使用NoActionBar主題,一般預設加載這個布局。
layoutResource = R.layout.screen_simple;
// System.out.println("Simple!");
}
View in = mLayoutInflater.inflate(layoutResource, null);
decor.addView(in, new ViewGroup.LayoutParams(MATCH_PARENT, MATCH_PARENT));
}
而screen_simple的預設布局就是這樣
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
android:orientation="vertical">
<ViewStub android:id="@+id/action_mode_bar_stub"
android:inflatedId="@+id/action_mode_bar"
android:layout="@layout/action_mode_bar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="?attr/actionBarTheme" />
<FrameLayout
android:id="@android:id/content"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:foregroundInsidePadding="false"
android:foregroundGravity="fill_horizontal|top"
android:foreground="?android:attr/windowContentOverlay" />
</LinearLayout>
Measure過程
MeaureSpec
MeaureSpec的含義
MeasureSpec 是一個32位int,高兩位代表SpecMode,低30位代表SpecSize。
SpecMode 代表的測量模式
SpecSize 代表的是目前測量模式下的大小
private static boolean sUseBrokenMakeMeasureSpec = false;
private static final int MODE_SHIFT = 30;
//0x3=0b0011 ,這裡相當于将32位的最高兩位置1
private static final int MODE_MASK = 0x3 << MODE_SHIFT;
public static int makeMeasureSpec(int size, int mode) {
if (sUseBrokenMakeMeasureSpec) {
return size + mode;
} else {
return (size & ~MODE_MASK) | (mode & MODE_MASK);
}
}
public static int getMode(int measureSpec) {
return (measureSpec & MODE_MASK);
}
public static int getSize(int measureSpec) {
return (measureSpec & ~MODE_MASK);
}
SpecMode 的類型
- UNSPECIFIED 子view要多大給多大,用于系統内部
- EXACTLY 父容器已經知道子view多大,對應match_parent和具體值
- AT_MOST 父容器告訴子view的允許的最大值。對應wrap_content
MeasureSpec 和 LayoutParams 的對應關系
MeasureSpec 是由LayoutParams和父容器才能決定。
DecorView 的MeasureSpec是由視窗尺寸和自身LayoutParams來共同确定。
viewGroup 測量子view的代碼
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);
}
這裡可以發現核心方法是getChildMeasureSpec。是以
public static int getChildMeasureSpec(int spec, int padding, int childDimension) {
int specMode = MeasureSpec.getMode(spec);
int specSize = MeasureSpec.getSize(spec);
//這裡的size為子元素最大可用大小,為父容器大小減去已占用的空間
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:
if (childDimension >= 0) {
resultSize = childDimension;
resultMode = MeasureSpec.EXACTLY;
} else if (childDimension == LayoutParams.MATCH_PARENT) {
// Child wants to be our size. So be it.
resultSize = size;
resultMode = MeasureSpec.EXACTLY;
} else if (childDimension == LayoutParams.WRAP_CONTENT) {
// Child wants to determine its own size. It can't be
// bigger than us.
resultSize = size;
resultMode = MeasureSpec.AT_MOST;
}
break;
// Parent has imposed a maximum size on us
case MeasureSpec.AT_MOST:
if (childDimension >= 0) {
// Child wants a specific size... so be it
resultSize = childDimension;
resultMode = MeasureSpec.EXACTLY;
} else if (childDimension == LayoutParams.MATCH_PARENT) {
// Child wants to be our size, but our size is not fixed.
// Constrain child to not be bigger than us.
resultSize = size;
resultMode = 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;
resultMode = MeasureSpec.AT_MOST;
}
break;
// Parent asked to see how big we want to be
case MeasureSpec.UNSPECIFIED:
if (childDimension >= 0) {
// Child wants a specific size... let him have it
resultSize = childDimension;
resultMode = MeasureSpec.EXACTLY;
} else if (childDimension == LayoutParams.MATCH_PARENT) {
// Child wants to be our size... find out how big it should
// be
resultSize = View.sUseZeroUnspecifiedMeasureSpec ? 0 : size;
resultMode = MeasureSpec.UNSPECIFIED;
} else if (childDimension == LayoutParams.WRAP_CONTENT) {
// Child wants to determine its own size.... find out how
// big it should be
resultSize = View.sUseZeroUnspecifiedMeasureSpec ? 0 : size;
resultMode = MeasureSpec.UNSPECIFIED;
}
break;
}
return MeasureSpec.makeMeasureSpec(resultSize, resultMode);
}
上面的代碼雖然很長,但是很簡單。表達的内容如下圖
childLayoutParams和parentSpecMode | EXACTLY | AT_MOST | UNSPECIFED |
---|---|---|---|
dp/px | EXACTLY/childSize | EXACTLY/childSize | EXACTLY/childSize |
match_parent | EXACTLY/parentSize | AT_MOST/parentSize | UNSPECIFED/0 |
wrap_content | AT_MOST/parentSize | AT_MOST/parentSize | UNSPECIFED/0 |
LinearLayout Measure 示例
首先看onMeasure
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
if (mOrientation == VERTICAL) {
measureVertical(widthMeasureSpec, heightMeasureSpec);
} else {
measureHorizontal(widthMeasureSpec, heightMeasureSpec);
}
}
這裡可以看到,根據LinearLayout布局方向的不同,分了兩個方法。但其實兩個方法是差不多的。我們這裡以measureVertical為例. 截取其中最核心的方法
for (int i = 0; i < count; ++i) {
final View child = getVirtualChildAt(i);
...
//這裡調用child的measure。這裡第四個參數是已經使用的寬度,由于這裡是縱向線性布局,是以寬度是childen獨占,
//是以已使用的width 為0,最後一個為height,這裡暫不讨論比重,當比重為0時,傳入的已使用高度,即為mTotalLength
measureChildBeforeLayout(
child, i, widthMeasureSpec, 0, heightMeasureSpec,
totalWeight == 0 ? mTotalLength : 0);
if (oldHeight != Integer.MIN_VALUE) {
lp.height = oldHeight;
}
final int childHeight = child.getMeasuredHeight();
final int totalLength = mTotalLength;
//更新已占用的長度,包含子元素本身的長度和margin.
mTotalLength = Math.max(totalLength, totalLength + childHeight + lp.topMargin +
lp.bottomMargin + getNextLocationOffset(child));
LinearLayout在更新完所有子元素的寬高後,LinearLayout會測量自己的寬高
mTotalLength += mPaddingTop + mPaddingBottom;
int heightSize = mTotalLength;
// Check against our minimum height
heightSize = Math.max(heightSize, getSuggestedMinimumHeight());
// Reconcile our calculated size with the heightMeasureSpec
//這裡如果測量模式為EXACTLY ,或者AT_MOST模式specSize 小于heightSize,那麼最後layout的高度為specSize
//其他情況下,高度都是為heightSize
int heightSizeAndState = resolveSizeAndState(heightSize, heightMeasureSpec, 0);
heightSize = heightSizeAndState & MEASURED_SIZE_MASK;
setMeasuredDimension(resolveSizeAndState(maxWidth, widthMeasureSpec, childState),
heightSizeAndState);
擷取view寬高的時機
由于view和activity的生命周期,并不是同步方法。我們無法在activity的某個生命周期中,确定view一定繪制完成。如果view還沒有測量完畢,那麼我們擷取的寬高均為0
根據書上所示,我們在以下時機可以擷取view的寬高
-
onWindowFocusChanged
含義是:view已經初始化完畢。當Activity得到和失去焦點均會被調用
-
view.post(runnable)
通過post将runnable投遞到消息隊列的尾部,等Looper調用此runnable的時候,view已經初始化好了
-
ViewTreeObserver
使用ViewTreeObserver裡面的諸多回調都可以完成此功能。伴随着View樹的改變,回調會多次調用
-
view.measure
手動對measure 進行測繪。如果view為固定的寬高或者wrap_content 則可以采用此方法。
由于手動measure 方法相當複雜,是以貼出相關代碼
view 為固定寬高時,假設為100,則:
int widthMeasureSpec= View.MeasureSpec.makeMeasureSpec(100, View.MeasureSpec.EXACTLY);
int heightMeasureSpec= View.MeasureSpec.makeMeasureSpec(100, View.MeasureSpec.EXACTLY);
view.measure(widthMeasureSpec,heightMeasureSpec);
wrap_content:
int widthMeasureSpec= View.MeasureSpec.makeMeasureSpec((1<<30)-1, View.MeasureSpec.AT_MOST);
int heightMeasureSpec= View.MeasureSpec.makeMeasureSpec((1<<30)-1, View.MeasureSpec.AT_MOST);
view.measure(widthMeasureSpec,heightMeasureSpec);
這裡我們假設view的父控件的寬高都是view 的寬高最大值,這樣擷取wrap_content是合理的。
注意 :如果在view以後測繪完成以後,手動調用measure方法,并且參數傳入錯誤的話,可能會導緻view按照錯誤的參數去重新繪制。
layout過程
layout 的過程和measure類似,都是先調用view的layout 方法。在layout方法中又會調用onlayout方法。
public void layout(int l, int t, int r, int b) {
if ((mPrivateFlags3 & PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT) != 0) {
onMeasure(mOldWidthMeasureSpec, mOldHeightMeasureSpec);
mPrivateFlags3 &= ~PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT;
}
int oldL = mLeft;
int oldT = mTop;
int oldB = mBottom;
int oldR = mRight;
//這裡将新的位置設定給view,并重新整理view
boolean changed = isLayoutModeOptical(mParent) ?
setOpticalFrame(l, t, r, b) : setFrame(l, t, r, b);
if (changed || (mPrivateFlags & PFLAG_LAYOUT_REQUIRED) == PFLAG_LAYOUT_REQUIRED) {
//這裡調用了onLayout.
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;
mPrivateFlags3 |= PFLAG3_IS_LAID_OUT;
}
而onLayout在view和viewgroup中均沒有具體的實作,是以我們還是看LinearLayout
@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
if (mOrientation == VERTICAL) {
layoutVertical(l, t, r, b);
} else {
layoutHorizontal(l, t, r, b);
}
}
這裡我們和measure一樣,還是選擇layoutVertical方法來分析。
void layoutVertical(int left, int top, int right, int bottom) {
//...
final int count = getVirtualChildCount();
//...
for (int i = 0; i < count; i++) {
final View child = getVirtualChildAt(i);
if (child == null) {
childTop += measureNullChild(i);
} else if (child.getVisibility() != GONE) {
final int childWidth = child.getMeasuredWidth();
final int childHeight = child.getMeasuredHeight();
final LinearLayout.LayoutParams lp =
(LinearLayout.LayoutParams) child.getLayoutParams();
//....
if (hasDividerBeforeChildAt(i)) {
childTop += mDividerHeight;
}
childTop += lp.topMargin;
//這裡就調用子元素的layout方法。而這裡傳遞給子元素的寬度和高度就是childWidth和childHeight
setChildFrame(child, childLeft, childTop + getLocationOffset(child),
childWidth, childHeight);
//這裡childTop是不斷增大的,每次都加上這次的childHeight
childTop += childHeight + lp.bottomMargin + getNextLocationOffset(child);
i += getChildrenSkipCount(child, i);
}
}
}
這裡可以看到傳遞給子元素的寬度和高度就是childWidth和childHeight.而在上面的代碼中
final int childWidth = child.getMeasuredWidth();
final int childHeight = child.getMeasuredHeight();
是以,這裡可以看到最終傳遞到給子元素的寬度和高度,就是MeasureWidth和MeasureHeight。
是以,我們可以認為在一般的view中,最終的寬高就是MeasureWidth和MeasureHeight。除非我們在layout中故意重寫,最終傳入的寬高。
draw過程
這裡我們先看view的draw的源碼
public void draw(Canvas canvas) {
final int privateFlags = mPrivateFlags;
final boolean dirtyOpaque = (privateFlags & PFLAG_DIRTY_MASK) == PFLAG_DIRTY_OPAQUE &&
(mAttachInfo == null || !mAttachInfo.mIgnoreDirtyState);
mPrivateFlags = (privateFlags & ~PFLAG_DIRTY_MASK) | PFLAG_DRAWN;
/*
* 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)
*/
/*
* 上面的話翻譯過來就是
* 繪制背景
* 繪制自己
* 繪制children
* 繪制裝飾
*/
// 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
//繪制children
dispatchDraw(canvas);
// Overlay is part of the content and draws beneath Foreground
if (mOverlay != null && !mOverlay.isEmpty()) {
mOverlay.getOverlayView().dispatchDraw(canvas);
}
// Step 6, draw decorations (foreground, scrollbars)
//繪制裝飾
onDrawForeground(canvas);
// we're done...
return;
}
/*
* Here we do the full fledged routine...
* (this is an uncommon case where speed matters less,
* this is why we repeat some of the tests that have been
* done above)
*/
boolean drawTop = false;
boolean drawBottom = false;
boolean drawLeft = false;
boolean drawRight = false;
float topFadeStrength = 0.0f;
float bottomFadeStrength = 0.0f;
float leftFadeStrength = 0.0f;
float rightFadeStrength = 0.0f;
// Step 2, save the canvas' layers
int paddingLeft = mPaddingLeft;
final boolean offsetRequired = isPaddingOffsetRequired();
if (offsetRequired) {
paddingLeft += getLeftPaddingOffset();
}
int left = mScrollX + paddingLeft;
int right = left + mRight - mLeft - mPaddingRight - paddingLeft;
int top = mScrollY + getFadeTop(offsetRequired);
int bottom = top + getFadeHeight(offsetRequired);
if (offsetRequired) {
right += getRightPaddingOffset();
bottom += getBottomPaddingOffset();
}
final ScrollabilityCache scrollabilityCache = mScrollCache;
final float fadeHeight = scrollabilityCache.fadingEdgeLength;
int length = (int) fadeHeight;
// clip the fade length if top and bottom fades overlap
// overlapping fades produce odd-looking artifacts
if (verticalEdges && (top + length > bottom - length)) {
length = (bottom - top) / 2;
}
// also clip horizontal fades if necessary
if (horizontalEdges && (left + length > right - length)) {
length = (right - left) / 2;
}
if (verticalEdges) {
topFadeStrength = Math.max(0.0f, Math.min(1.0f, getTopFadingEdgeStrength()));
drawTop = topFadeStrength * fadeHeight > 1.0f;
bottomFadeStrength = Math.max(0.0f, Math.min(1.0f, getBottomFadingEdgeStrength()));
drawBottom = bottomFadeStrength * fadeHeight > 1.0f;
}
if (horizontalEdges) {
leftFadeStrength = Math.max(0.0f, Math.min(1.0f, getLeftFadingEdgeStrength()));
drawLeft = leftFadeStrength * fadeHeight > 1.0f;
rightFadeStrength = Math.max(0.0f, Math.min(1.0f, getRightFadingEdgeStrength()));
drawRight = rightFadeStrength * fadeHeight > 1.0f;
}
saveCount = canvas.getSaveCount();
int solidColor = getSolidColor();
if (solidColor == 0) {
final int flags = Canvas.HAS_ALPHA_LAYER_SAVE_FLAG;
if (drawTop) {
canvas.saveLayer(left, top, right, top + length, null, flags);
}
if (drawBottom) {
canvas.saveLayer(left, bottom - length, right, bottom, null, flags);
}
if (drawLeft) {
canvas.saveLayer(left, top, left + length, bottom, null, flags);
}
if (drawRight) {
canvas.saveLayer(right - length, top, right, bottom, null, flags);
}
} else {
scrollabilityCache.setFadeColor(solidColor);
}
// Step 3, draw the content
if (!dirtyOpaque) onDraw(canvas);
// Step 4, draw the children
dispatchDraw(canvas);
// Step 5, draw the fade effect and restore layers
final Paint p = scrollabilityCache.paint;
final Matrix matrix = scrollabilityCache.matrix;
final Shader fade = scrollabilityCache.shader;
if (drawTop) {
matrix.setScale(1, fadeHeight * topFadeStrength);
matrix.postTranslate(left, top);
fade.setLocalMatrix(matrix);
p.setShader(fade);
canvas.drawRect(left, top, right, top + length, p);
}
if (drawBottom) {
matrix.setScale(1, fadeHeight * bottomFadeStrength);
matrix.postRotate(180);
matrix.postTranslate(left, bottom);
fade.setLocalMatrix(matrix);
p.setShader(fade);
canvas.drawRect(left, bottom - length, right, bottom, p);
}
if (drawLeft) {
matrix.setScale(1, fadeHeight * leftFadeStrength);
matrix.postRotate(-90);
matrix.postTranslate(left, top);
fade.setLocalMatrix(matrix);
p.setShader(fade);
canvas.drawRect(left, top, left + length, bottom, p);
}
if (drawRight) {
matrix.setScale(1, fadeHeight * rightFadeStrength);
matrix.postRotate(90);
matrix.postTranslate(right, top);
fade.setLocalMatrix(matrix);
p.setShader(fade);
canvas.drawRect(right - length, top, right, bottom, p);
}
canvas.restoreToCount(saveCount);
// Overlay is part of the content and draws beneath Foreground
if (mOverlay != null && !mOverlay.isEmpty()) {
mOverlay.getOverlayView().dispatchDraw(canvas);
}
// Step 6, draw decorations (foreground, scrollbars)
onDrawForeground(canvas);
}
在view 的方法中,有個方法需要特别注意一下,就是setWillNotDraw。如果setWillNotDraw開啟以後,系統将預設優化,對自身不再繪制。在viewgroup中,是預設打開了此配置。如果我們自定義的viewgroup需要繪制自身,則需要打開此配置。
自定義view注意事項
- 直接繼承view ,需要實作warp_content支援
- 需要實作padding的支援
- 直接使用view内部handler
- 線程和動畫,注意生命周期onAttachedToWindow和onDetachedFromWindow
- 嵌套滑動沖突