前面的文章中我們介紹了DecorView,ViewRoot裁奇,并且我們介紹了DecorView如何添加到Window中姻成。那么接著,我們就繼續(xù)來(lái)看看乒躺,DecorView添加后,是如何進(jìn)行后續(xù)的View繪制過(guò)程呢低缩?本文源碼均來(lái)自API 24聪蘸。
首先我們又要來(lái)回顧一下ViewRoot這個(gè)類,這個(gè)類是一個(gè)非常非常重要的類表制。它是Window和View的紐帶。這個(gè)類在之前的介紹中已經(jīng)分析了其中一個(gè)功能:負(fù)責(zé)接收觸摸控乾,鍵盤事件等么介,并將它們進(jìn)行傳遞到我們的Activity,子View等。現(xiàn)在我們來(lái)詳細(xì)介紹另一個(gè)功能:負(fù)責(zé)觸發(fā)View的繪制流程(即measure,layout,draw三大過(guò)程)蜕衡。
簡(jiǎn)單介紹完了ViewRoot壤短,接下來(lái)我們來(lái)開始跟著源碼分析:
首先在之前的window.addView()將decorView添加到Window的過(guò)程中創(chuàng)建了ViewRoot,然后調(diào)用了viewRoot.setView()將window加入到windowManager。那么之前在setView()中我們只分析了添加的相關(guān)代碼,現(xiàn)在我們回過(guò)頭來(lái)看看其中的繪制代碼:
public void setView(View view, WindowManager.LayoutParams attrs, View panelParentView) {
synchronized (this) {
if (mView == null) {
//將頂層視圖DecorView賦值給全局的mView
mView = view;
..//其他代碼
//標(biāo)記已添加DecorView
mAdded = true;
.............
//請(qǐng)求布局
requestLayout();
..//其他代碼
}
}
在上面的文章中我們可以看到調(diào)用了我們熟悉的requestLayout()方法久脯。我們跟進(jìn)去看看:
@Override
public void requestLayout() {
if (!mHandlingLayoutInLayoutRequest) {
checkThread();
mLayoutRequested = true;
scheduleTraversals();
}
}
上面調(diào)用了幾個(gè)方法纳胧,首先是checkThread()方法,我們跟進(jìn)去看看:
void checkThread() {
if (mThread != Thread.currentThread()) {
throw new CalledFromWrongThreadException(
"Only the original thread that created a view hierarchy can touch its views.");
}
}
我們可以看到在這里進(jìn)行了線程檢查帘撰,這里也就是所謂的我們經(jīng)常說(shuō)的只有主線程才能操作UI的問(wèn)題跑慕。但是其實(shí)看看這里的判斷條件。并沒有明確判斷說(shuō)當(dāng)前線程是主線程摧找。而且通過(guò)mThread是否是當(dāng)前線程來(lái)判斷核行。那么我們?nèi)タ纯催@個(gè)mThread是什么?
上圖中可以看出蹬耘,是在新建ViewRoot的時(shí)候?qū)?dāng)前線程賦給mThread芝雪。而我們的ViewRoot一般都是內(nèi)部在主線程創(chuàng)建的。所以W厶Α3拖怠!H缟浮堡牡!所謂的子線程操作UI并不準(zhǔn)確!理想情況下要是我們?cè)谧泳€程中創(chuàng)建ViewRoot,那么我們?cè)谥骶€程操作UI豈不是會(huì)報(bào)錯(cuò)妙黍?
上面的可以說(shuō)是正餐點(diǎn)心悴侵,我們不深究,繼續(xù)往下探索繪制流程拭嫁。
在檢查線程后可免,執(zhí)行了 scheduleTraversals()方法,我們就繼續(xù)看看:
void scheduleTraversals() {
if (!mTraversalScheduled) {
mTraversalScheduled = true;
mTraversalBarrier = mHandler.getLooper().getQueue().postSyncBarrier();
mChoreographer.postCallback(
Choreographer.CALLBACK_TRAVERSAL, mTraversalRunnable, null);
if (!mUnbufferedInputDispatch) {
scheduleConsumeBatchedInput();
}
notifyRendererOfFramePending();
pokeDrawLockIfNeeded();
}
}
我們看到在上面調(diào)用了mChoreographer.postCallback(
Choreographer.CALLBACK_TRAVERSAL, mTraversalRunnable, null);方法做粤,在這里其實(shí)就是通過(guò)handler的方式將mTraversalRunnable進(jìn)行異步執(zhí)行浇借,感興趣的同學(xué)可以去看看。我們看看mTraversalRunnable里面的執(zhí)行體代碼:
final class TraversalRunnable implements Runnable {
@Override
public void run() {
doTraversal();
}
}
可以看到怕品,只有一個(gè)doTraversal()方法:
void doTraversal() {
if (mTraversalScheduled) {
mTraversalScheduled = false;
mHandler.getLooper().getQueue().removeSyncBarrier(mTraversalBarrier);
if (mProfile) {
Debug.startMethodTracing("ViewAncestor");
}
performTraversals();
if (mProfile) {
Debug.stopMethodTracing();
mProfile = false;
}
}
}
我們看到又調(diào)用了performTraversals()方法,終于看到我們熟悉的方法了妇垢,基本上所有網(wǎng)上的各種資料開頭都是android的繪制過(guò)程從ViewRoot的performTraversals()開始。那么我們現(xiàn)在也終于知道了這個(gè)開始之前是怎么回事肉康。接下來(lái)我們就繼續(xù)一探究竟闯估,繼續(xù)跟入performTraversals()方法(貼出關(guān)鍵代碼,這個(gè)方法代碼估計(jì)有1千多行):
private void performTraversals() {
// cache mView since it is used so much below...
final View host = mView; //mView就是DecorView根布局
//是否正在遍歷
mIsInTraversal = true;
//是否馬上繪制View
mWillDrawSoon = true;
..//其他代碼
//希望的窗口的寬高
int desiredWindowWidth;
int desiredWindowHeight;
//Window的參數(shù)
WindowManager.LayoutParams lp = mWindowAttributes;
if (mFirst) {
mFullRedrawNeeded = true;
mLayoutRequested = true;
//如果窗口的類型是有狀態(tài)欄的吼和,那么頂層視圖DecorView所需要窗口的寬度和高度就是除了狀態(tài)欄
if (lp.type == WindowManager.LayoutParams.TYPE_STATUS_BAR_PANEL
|| lp.type == WindowManager.LayoutParams.TYPE_INPUT_METHOD) {
// NOTE -- system code, won't try to do compat mode.
Point size = new Point();
mDisplay.getRealSize(size);
desiredWindowWidth = size.x;
desiredWindowHeight = size.y;
} else {//否則頂層視圖DecorView所需要窗口的寬度和高度就是整個(gè)屏幕的寬高
DisplayMetrics packageMetrics =
mView.getContext().getResources().getDisplayMetrics();
desiredWindowWidth = packageMetrics.widthPixels;
desiredWindowHeight = packageMetrics.heightPixels;
}
}
..//其他代碼
//在構(gòu)造方法中mFirst已經(jīng)設(shè)置為true涨薪,表示是否是第一次繪制DecorView
..//其他代碼
//獲得view寬高的測(cè)量規(guī)格,mWidth和mHeight表示窗口的寬高炫乓,lp.widthhe和lp.height表示DecorView根布局寬和高
int childWidthMeasureSpec = getRootMeasureSpec(mWidth, lp.width);
int childHeightMeasureSpec = getRootMeasureSpec(mHeight, lp.height);
// Ask host how big it wants to be
//執(zhí)行測(cè)量操作
performMeasure(childWidthMeasureSpec, childHeightMeasureSpec);
..//其他代碼
//執(zhí)行布局操作
performLayout(lp, desiredWindowWidth, desiredWindowHeight);
..//其他代碼
//執(zhí)行繪制操作
performDraw();
}
從上面代碼可以看到整個(gè)路程還是很清晰的刚夺,從上到下先后調(diào)用了performMeasure(), performLayout()献丑,performDraw()方法來(lái)完成整個(gè)繪制流程。我們先來(lái)看看performMeasure()方法侠姑,首先方法有兩個(gè)參數(shù)创橄,我們來(lái)看看代碼怎么設(shè)置的。都執(zhí)行了getRootMeasureSpec()方法莽红,我們進(jìn)去看看:
private static int getRootMeasureSpec(int windowSize, int rootDimension) {
int measureSpec;
switch (rootDimension) {
case ViewGroup.LayoutParams.MATCH_PARENT:
// Window can't resize. Force root view to be windowSize.
measureSpec = MeasureSpec.makeMeasureSpec(windowSize, MeasureSpec.EXACTLY);
break;
case ViewGroup.LayoutParams.WRAP_CONTENT:
// Window can resize. Set max size for root view.
measureSpec = MeasureSpec.makeMeasureSpec(windowSize, MeasureSpec.AT_MOST);
break;
default:
// Window wants to be an exact size. Force root view to be that size.
measureSpec = MeasureSpec.makeMeasureSpec(rootDimension, MeasureSpec.EXACTLY);
break;
}
return measureSpec;
}
我們先來(lái)簡(jiǎn)單地介紹下MeasureSpec的概念妥畏。
MeasureSpec是一個(gè)32位整數(shù),由SpecMode和SpecSize兩部分組成船老,其中咖熟,高2位為SpecMode,低30位為SpecSize柳畔。SpecMode為測(cè)量模式馍管,SpecSize為相應(yīng)測(cè)量模式下的測(cè)量尺寸。View(包括普通View和ViewGroup)的SpecMode由本View的LayoutParams結(jié)合父View的MeasureSpec生成薪韩。
SpecMode的取值可為以下三種:
EXACTLY: 對(duì)子View提出了一個(gè)確切的建議尺寸(SpecSize)确沸;
AT_MOST: 子View的大小不得超過(guò)SpecSize;
UNSPECIFIED: 對(duì)子View的尺寸不作限制俘陷,通常用于系統(tǒng)內(nèi)部罗捎。
介紹完了我們來(lái)分析。getRootMeasureSpec()方法主要作用是在整個(gè)窗口的基礎(chǔ)上計(jì)算出root view(頂層視圖DecorView)的測(cè)量規(guī)格拉盾,相當(dāng)于由Window和自身參數(shù)決定自己的measureSpec桨菜。該方法的兩個(gè)參數(shù)分別表示:
?在這里我們看到,首先根據(jù)rootDimension來(lái)設(shè)置DecorView的測(cè)量模式捉偏。一般對(duì)于Activity來(lái)說(shuō)倒得,Window 是MATCH_PARENT,對(duì)于Dialog來(lái)說(shuō),Window 是WRAP_CONTENT夭禽。因此所以對(duì)于Activity分析霞掺,執(zhí)行case 為MATCH_PARENT的代碼,那么將設(shè)置DecorView的measureSpec的模式為EXACTLY+屏幕尺寸讹躯。設(shè)置完后菩彬,該方法返回。然后繼續(xù)執(zhí)行 performMeasure()方法潮梯。至此我們就要開始進(jìn)行三大流程之一的測(cè)量流程骗灶。
一.Measure流程
Measure流程就是確定我們的View的大小,是全屏顯示秉馏?還是具體大小等等矿卑。
我們來(lái)看看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);
}
}
在這里調(diào)用了mView.measure()方法,而mView就是指的decorView沃饶。
我們跟進(jìn)去看看:
public final void measure(int widthMeasureSpec, int heightMeasureSpec) {
..//其他代碼
//如果上一次的測(cè)量規(guī)格和這次不一樣母廷,那么重新測(cè)量大小
if ((mPrivateFlags & PFLAG_FORCE_LAYOUT) == PFLAG_FORCE_LAYOUT ||
widthMeasureSpec != mOldWidthMeasureSpec ||
heightMeasureSpec != mOldHeightMeasureSpec) {
..//其他代碼
if (cacheIndex < 0 || sIgnoreMeasureCache) {
// measure ourselves, this should set the measured dimension flag back
----------代碼1處--------------
onMeasure(widthMeasureSpec, heightMeasureSpec);
mPrivateFlags3 &= ~PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT;
} else {
long value = mMeasureCache.valueAt(cacheIndex);
// Casting a long to int drops the high 32 bits, no mask needed
setMeasuredDimensionRaw((int) (value >> 32), (int) value);
mPrivateFlags3 |= PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT;
}
mPrivateFlags |= PFLAG_LAYOUT_REQUIRED;
}
----------代碼2處--------------
mOldWidthMeasureSpec = widthMeasureSpec;
mOldHeightMeasureSpec = heightMeasureSpec;
}
首先我們貼出關(guān)鍵代碼,首先方法里會(huì)進(jìn)行判斷糊肤,如果當(dāng)前的measureSpec和上次的不一樣琴昆,那么說(shuō)明需要進(jìn)行測(cè)量。在代碼1處執(zhí)行了onMeasure()方法馆揉。沒錯(cuò)业舍,這個(gè)方法就是我們自定義View中經(jīng)常重寫的onMeasure()方法。代碼2處是將當(dāng)前設(shè)置的measureSpec賦值給mOldxxxMeasureSpec保存下升酣。我們繼續(xù)跟進(jìn)去onMeasure()默認(rèn)實(shí)現(xiàn)的方法:
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
setMeasuredDimension(getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec),
getDefaultSize(getSuggestedMinimumHeight(), heightMeasureSpec));
}
調(diào)用了setMeasuredDimension()方法舷暮。通過(guò)測(cè)量調(diào)用到這個(gè)方法時(shí)表示測(cè)量已經(jīng)結(jié)束。我們來(lái)看看其中的參數(shù)相關(guān)的方法,首先看看getDefaultSize()方法:
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;
}
傳入的第一個(gè)參數(shù)為size,第二個(gè)measureSpec,這些都很簡(jiǎn)單噩茄。我們來(lái)看看代碼下面,首先得到DecorView的測(cè)量模式和測(cè)量大小。然后根據(jù)測(cè)量模式進(jìn)行處理绩聘。在前面我們已經(jīng)知道decorView的測(cè)量模式為EXACTLY模式沥割。因此這里直接返回DecorView之前的測(cè)量大小。
而如果是UNSPECIFIED模式凿菩,那么將傳入的size返回机杜。那么這個(gè)size是什么呢?我們回到之前調(diào)用getDefaultSize()的地方看看衅谷,發(fā)現(xiàn)size是由getSuggestedMinimumWidth()方法產(chǎn)生椒拗,我們?cè)倮^續(xù)看看:
protected int getSuggestedMinimumWidth() {
return (mBackground == null) ? mMinWidth : max(mMinWidth, mBackground.getMinimumWidth());
}
在這里看到是一個(gè)三目表達(dá)式用來(lái)獲取View屬性當(dāng)中的最小值,也就是 android:minWidth和 android:minHeight的值获黔,前提是View沒有設(shè)置背景屬性蚀苛。如果設(shè)置了背景圖,那么就在最小值和背景的最小值中間取最大值肢执。
至此我們已經(jīng)把參數(shù)相關(guān)的方法分析完了,參數(shù)設(shè)置完后調(diào)用setMeasuredDimension()方法即可完成測(cè)量枉阵。
至此我們就將默認(rèn)實(shí)現(xiàn)的onMeasure()方法分析完了。
因?yàn)槲覀儸F(xiàn)在分析到DecorView的測(cè)量预茄。所以我們來(lái)看看DecorView的測(cè)量兴溜。DecorView繼承自FrameLayout。我們來(lái)看看FrameLayout的onMeasure()方法:
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
..//其他代碼
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
..//其他代碼
}
去掉其他的代碼耻陕,我們看到調(diào)用了父類的onMeasure(),我們跟進(jìn)去看看FrameLayout的onMeasure()方法:
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int count = getChildCount();
..//其他代碼
for (int i = 0; i < count; i++) {
final View child = getChildAt(i);
if (mMeasureAllChildren || child.getVisibility() != GONE) {
measureChildWithMargins(child, widthMeasureSpec, 0, heightMeasureSpec, 0);
final LayoutParams lp = (LayoutParams) child.getLayoutParams();
maxWidth = Math.max(maxWidth,
child.getMeasuredWidth() + lp.leftMargin + lp.rightMargin);
maxHeight = Math.max(maxHeight,
child.getMeasuredHeight() + lp.topMargin + lp.bottomMargin);
childState = combineMeasuredStates(childState, child.getMeasuredState());
if (measureMatchParentChildren) {
if (lp.width == LayoutParams.MATCH_PARENT ||
lp.height == LayoutParams.MATCH_PARENT) {
mMatchParentChildren.add(child);
}
}
}
}
// Account for padding too
maxWidth += getPaddingLeftWithForeground() + getPaddingRightWithForeground();
maxHeight += getPaddingTopWithForeground() + getPaddingBottomWithForeground();
// Check against our minimum height and width
maxHeight = Math.max(maxHeight, getSuggestedMinimumHeight());
maxWidth = Math.max(maxWidth, getSuggestedMinimumWidth());
// Check against our foreground's minimum height and width
final Drawable drawable = getForeground();
if (drawable != null) {
maxHeight = Math.max(maxHeight, drawable.getMinimumHeight());
maxWidth = Math.max(maxWidth, drawable.getMinimumWidth());
}
setMeasuredDimension(resolveSizeAndState(maxWidth, widthMeasureSpec, childState),
resolveSizeAndState(maxHeight, heightMeasureSpec,
childState << MEASURED_HEIGHT_STATE_SHIFT));
..//其他代碼
}
我們貼出關(guān)鍵代碼拙徽,可以看到首先是一個(gè)for循環(huán)遍歷當(dāng)前View的子View。然后如果需要測(cè)量所有子View并且這個(gè)子View可見诗宣。會(huì)調(diào)用measureChildWithMargins()方法來(lái)進(jìn)行測(cè)量子View膘怕。我們跟進(jìn)去看看:
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);
}
我們看到首先調(diào)用getChildMeasureSpec()方法來(lái)獲取當(dāng)前子View的measureSpec。然后調(diào)用measure()方法進(jìn)行測(cè)量召庞。我們先來(lái)看看getChildMeasureSpec()方法源碼:
public static int getChildMeasureSpec(int spec, int padding, int childDimension) {
//得到父布局的測(cè)量模式和測(cè)量大小
int specMode = MeasureSpec.getMode(spec);
int specSize = MeasureSpec.getSize(spec);
//定義size變量岛心,表示0和父類大小減去padding之間的最大值
//padding表示父布局的padding和當(dāng)前子View的margin
//如果是求widthMeasureSpec,則是父布局的左右padding和左右margin来破,heightMeasure同理
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;
}
//noinspection ResourceType
return MeasureSpec.makeMeasureSpec(resultSize, resultMode);
}
代碼不算長(zhǎng),我們來(lái)看看忘古。前面的變量說(shuō)明已經(jīng)在代碼中給出徘禁。傳入的childDimension在上面的代碼中可以看出就是當(dāng)前子View的LayoutParams的寬或者高。
然后根據(jù)是一段通過(guò)父類測(cè)量模式判斷的switch方法髓堪。我們拿EXACTLY模式來(lái)看一下送朱。如果父布局是EXACTLY模式,那么判斷當(dāng)前子View的寬度(假設(shè)當(dāng)前方法是求widthMeasureSpec)是否大于0干旁,如果大于0驶沼,那么結(jié)果就是子view的大小+ EXACTLY模式。如果子View的寬度是MATCH_PARENT争群,結(jié)果就是父類的大小+EXACTLY模式回怜。如果子View的寬度是WRAP_CONTENT,結(jié)果就是父類的大小+ AT_MOST模式祭阀。另外兩種情況就不再具體分析鹉戚,讀者自行查看即可。
注:上圖來(lái)自任玉剛大神的《Android開發(fā)藝術(shù)探索》专控。
在得到當(dāng)前子View的widthMeasureSpec和heightMeasureSpec后抹凳。調(diào)用child.measure(childWidthMeasureSpec, childHeightMeasureSpec)方法竣灌。然后又進(jìn)行上面從measure()方法開始的流程渺氧。而我們上面分析onMeasure()方法是ViewGroup的,所以會(huì)通過(guò)循環(huán)測(cè)量所有的子View再進(jìn)行自身的測(cè)量后控。
總結(jié)一下測(cè)量過(guò)程:
- View的measure方法是final類型的柏蘑,子類不可以重寫幸冻,子類可以通過(guò)重寫onMeasure方法來(lái)測(cè)量自己的大小。
- View測(cè)量結(jié)束的標(biāo)志是調(diào)用了setMeasuredDimension()方法咳焚,因此需要在自定義的View中重寫onMeasure方法洽损,在測(cè)量結(jié)束之前必須調(diào)用setMeasuredDimension方法測(cè)量才有效果。
- 在Activity生命周期onCreate()和onResume()方法中調(diào)用View.getMeasuredWidth()和View.getMeasuredHeight()返回值為0革半,因?yàn)镈ecorView添加到PhoneWindow窗口后才會(huì)開始測(cè)量所有View碑定。而在Activity生命周期onCreate(),onResume()執(zhí)行前performResumeActivity還未執(zhí)行,因此調(diào)用View.getMeasuredHeight()返回值為0又官。
- 子視圖View的大小是由父容器View和子視圖View布局共同決定的延刘。
二.Layout過(guò)程
上面我們分析完了測(cè)量流程,接下來(lái)我們分析Layout流程六敬。Layout流程就是確定子View的擺放位置碘赖。比如應(yīng)該擺放在父布局的左邊?還是右邊?等等這些問(wèn)題普泡。
接著本文最開始ViewRootImpl的performTraversals()方法的代碼播掷,執(zhí)行完performMeasure()方法后,會(huì)接著執(zhí)行performLayout()方法劫哼,我們?nèi)タ纯创a:
private void performLayout(WindowManager.LayoutParams lp, int desiredWindowWidth,
int desiredWindowHeight) {
mLayoutRequested = false;
mScrollMayChange = true;
mInLayout = true;
final View host = mView;
..//其他代碼
host.layout(0, 0, host.getMeasuredWidth(), host.getMeasuredHeight());
..//其他代碼
mInLayout = false;
..//其他代碼
}
我們看到調(diào)用了layout方法叮趴。而host就是DecorView。我們繼續(xù)跟進(jìn)去看看:
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;
mPrivateFlags3 |= PFLAG3_IS_LAID_OUT;
}
首先將當(dāng)前view舊的參數(shù)保存权烧,然后定義了一個(gè)changed的布爾值,用來(lái)判斷View的相關(guān)寬高是否和之前的一樣伤溉。setOpticalFrame()方法里面還是調(diào)用了setFrame()方法般码,我們就重點(diǎn)來(lái)看setFrame()方法:
protected boolean setFrame(int left, int top, int right, int bottom) {
boolean changed = false;
..//其他代碼
//如果有一條邊的值和之前的不同,表示當(dāng)前View的參數(shù)已修改
if (mLeft != left || mRight != right || mTop != top || mBottom != bottom) {
changed = true;
// Remember our drawn bit
int drawn = mPrivateFlags & PFLAG_DRAWN;
int oldWidth = mRight - mLeft;
int oldHeight = mBottom - mTop;
int newWidth = right - left;
int newHeight = bottom - top;
boolean sizeChanged = (newWidth != oldWidth) || (newHeight != oldHeight);
..//其他代碼
mLeft = left;
mTop = top;
mRight = right;
mBottom = bottom;
mRenderNode.setLeftTopRightBottom(mLeft, mTop, mRight, mBottom);
if (sizeChanged) {
sizeChange(newWidth, newHeight, oldWidth, oldHeight);
}
..//其他代碼
return changed;
}
貼出關(guān)鍵代碼乱顾,我們可以看到板祝,如果我們當(dāng)前View的左右上下四條邊中的一條發(fā)生了變化,那么就會(huì)執(zhí)行if代碼塊里面的代碼走净。將mLeft等四條邊的值進(jìn)行更新券时。而mLeft等四個(gè)成員變量就正式表示當(dāng)前View的所處位置。在這里我們額外說(shuō)明一下伏伯,我們經(jīng)常在自定義View的時(shí)候使用getWidth()和getHeight()方法:
public final int getWidth() {
return mRight - mLeft;
}
public final int getHeight() {
return mBottom - mTop;
}
代碼如上橘洞,因此我們?cè)趏nMeasure()方法中調(diào)用得到結(jié)果為0的原因這是這樣。因?yàn)檫@幾個(gè)成員變量是在剛才的layout()方法中才變化说搅。分析完了setFrame()方法炸枣,我們接著往下看layout()方法。接下來(lái)會(huì)調(diào)用onLayout()方法:
protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
}
驚不驚喜弄唧?适肠?
意不意外?候引?
居然是空實(shí)現(xiàn)侯养??
沒錯(cuò)澄干,這是因此逛揩,系統(tǒng)并沒有默認(rèn)為我們實(shí)現(xiàn)onLayout(),而是由我們自由發(fā)揮傻寂。那我們?nèi)タ纯碫iewGroup息尺,看看它有沒有實(shí)現(xiàn)onLayout()方法:
@Override
protected abstract void onLayout(boolean changed,
int l, int t, int r, int b);
居然是一個(gè)抽象方法。其實(shí)并不意外疾掰,我們自定義ViewGroup的時(shí)候搂誉,必須實(shí)現(xiàn)onLayout()方法的原因也在這里。
那我們?nèi)タ纯碊ecorView呢静檬,它繼承自FrameLayout,我們?nèi)タ纯矗?/p>
@Override
protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
layoutChildren(left, top, right, bottom, false /* no force left gravity */);
}
void layoutChildren(int left, int top, int right, int bottom, boolean forceLeftGravity) {
final int count = getChildCount();
final int parentLeft = getPaddingLeftWithForeground();
final int parentRight = right - left - getPaddingRightWithForeground();
final int parentTop = getPaddingTopWithForeground();
final int parentBottom = bottom - top - getPaddingBottomWithForeground();
//遍歷所有子View
for (int i = 0; i < count; i++) {
final View child = getChildAt(i);
//如果子View的Visibility是GONE就不會(huì)設(shè)置炭懊,因此GONE的View是不會(huì)加載的
if (child.getVisibility() != GONE) {
final LayoutParams lp = (LayoutParams) child.getLayoutParams();
final int width = child.getMeasuredWidth();
final int height = child.getMeasuredHeight();
int childLeft;
int childTop;
int gravity = lp.gravity;
if (gravity == -1) {
gravity = DEFAULT_CHILD_GRAVITY;
}
final int layoutDirection = getLayoutDirection();
final int absoluteGravity = Gravity.getAbsoluteGravity(gravity, layoutDirection);
final int verticalGravity = gravity & Gravity.VERTICAL_GRAVITY_MASK;
//通過(guò)這個(gè)switch確定child的left邊
switch (absoluteGravity & Gravity.HORIZONTAL_GRAVITY_MASK) {
case Gravity.CENTER_HORIZONTAL:
childLeft = parentLeft + (parentRight - parentLeft - width) / 2 +
lp.leftMargin - lp.rightMargin;
break;
case Gravity.RIGHT:
if (!forceLeftGravity) {
childLeft = parentRight - width - lp.rightMargin;
break;
}
case Gravity.LEFT:
default:
childLeft = parentLeft + lp.leftMargin;
}
//通過(guò)這個(gè)switch確定child的top邊
switch (verticalGravity) {
case Gravity.TOP:
childTop = parentTop + lp.topMargin;
break;
case Gravity.CENTER_VERTICAL:
childTop = parentTop + (parentBottom - parentTop - height) / 2 +
lp.topMargin - lp.bottomMargin;
break;
case Gravity.BOTTOM:
childTop = parentBottom - height - lp.bottomMargin;
break;
default:
childTop = parentTop + lp.topMargin;
}
//調(diào)用子View的layout()方法來(lái)設(shè)置子View的mLeft等四條邊
child.layout(childLeft, childTop, childLeft + width, childTop + height);
}
}
}
上面是FrameLayout的onLayout()方法并级,就只調(diào)用了一個(gè)layoutChildren()方法。具體解釋已經(jīng)在上面代碼中侮腹。最后調(diào)用 child.layout(childLeft, childTop, childLeft + width, childTop + height)來(lái)重復(fù)之前的流程嘲碧,我們就不再重復(fù)分析。
至此我們的layout流程也差不多分析完畢父阻。來(lái)先用一張圖總結(jié)一下愈涩。
- 真正確認(rèn)View的布局是在layout方法里實(shí)現(xiàn)的,并不是在onLayout()這個(gè)方法里面加矛。
- 必須在View布局完(也就是setFrame()方法)之后調(diào)用getHeight()和getWidth()方法獲取到的View的寬高才大于0履婉。
- ViewGroup的onLayout()方法是抽象的,因此我們自定義ViewGroup必須實(shí)現(xiàn)onLayout()方法斟览。
至此我們就分析完了layout流程毁腿,我們繼續(xù)接著分析最后一個(gè)步draw流程。
三.Draw
繪制流程通俗說(shuō)就是將我們的View像畫畫一樣將它們展現(xiàn)出來(lái)苛茂。
接著上面的performTraversals()方法已烤,執(zhí)行完了performMeasure(),performLayout()方法后,會(huì)接著執(zhí)行performDraw()方法開開始繪制流程妓羊,我們來(lái)看看代碼:
private void performDraw() {
..//其他代碼
try {
draw(fullRedrawNeeded);
} finally {
mIsDrawing = false;
Trace.traceEnd(Trace.TRACE_TAG_VIEW);
}
..//其他代碼
}
看到上面調(diào)用了draw()方法胯究,我們繼續(xù)跟進(jìn)去:
private boolean drawSoftware(Surface surface, AttachInfo attachInfo, int xoff, int yoff,
boolean scalingRequired, Rect dirty) {
// Draw with software renderer.
final Canvas canvas;
try {
//從surface對(duì)象中獲得canvas變量
canvas = mSurface.lockCanvas(dirty);
// If this bitmap's format includes an alpha channel, we
// need to clear it before drawing so that the child will
// properly re-composite its drawing on a transparent
// background. This automatically respects the clip/dirty region
// or
// If we are applying an offset, we need to clear the area
// where the offset doesn't appear to avoid having garbage
// left in the blank areas.
if (!canvas.isOpaque() || yoff != 0 || xoff != 0) {
canvas.drawColor(0, PorterDuff.Mode.CLEAR);
}
..//其他代碼
try {
//調(diào)整畫布的位置
canvas.translate(-xoff, -yoff);
if (mTranslator != null) {
mTranslator.translateCanvas(canvas);
}
canvas.setScreenDensity(scalingRequired ? mNoncompatDensity : 0);
attachInfo.mSetIgnoreDirtyState = false;
//調(diào)用View類中的成員方法draw開始繪制View視圖
mView.draw(canvas);
}
..//其他代碼
return true;
}
我們貼出關(guān)鍵代碼看到,最后調(diào)用了View的draw()方法侍瑟。我們繼續(xù)跟進(jìn):
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)
*/
// 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
dispatchDraw(canvas);
// Step 6, draw decorations (scrollbars)
onDrawScrollBars(canvas);
if (mOverlay != null && !mOverlay.isEmpty()) {
mOverlay.getOverlayView().dispatchDraw(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);
// Step 6, draw decorations (scrollbars)
onDrawScrollBars(canvas);
if (mOverlay != null && !mOverlay.isEmpty()) {
mOverlay.getOverlayView().dispatchDraw(canvas);
}
}
view的draw()方法源碼比較長(zhǎng)唐片,但是我們可以看到源碼里的注釋已經(jīng)為我們解釋清楚,繪制分為6步涨颜,第一步繪制背景费韭,第二步如果需要的話,保存canvas的圖層為了漸變效果做準(zhǔn)備庭瑰,第三步繪制自身內(nèi)容星持,第四步繪制子View,第五部如果需要繪制漸變效果并且restore圖層,第六步繪制裝飾物弹灭,比如滾動(dòng)條等督暂。
其中第二步和第五步不是必須的。我們來(lái)看看第三步繪制自己內(nèi)容和第四步繪制子View穷吮。
其中第三步調(diào)用了onDraw()方法逻翁,我們來(lái)看看:
protected void onDraw(Canvas canvas) {
}
我們看到這是一個(gè)空實(shí)現(xiàn)。其實(shí)也很容易理解捡鱼。不同的View類型有自己不同的內(nèi)容八回。因此在這里View這個(gè)父類是不能夠一概而論的。因此這個(gè)onDraw()方法的邏輯需要具體的View去實(shí)現(xiàn)。正是這樣缠诅,我們自定義View的時(shí)候都會(huì)重寫onDraw()方法溶浴。
而第四步繪制子View的時(shí)候調(diào)用了dispatchDraw()方法,我們跟進(jìn)去看看:
protected void dispatchDraw(Canvas canvas) {
}
dispatchDraw()也是一個(gè)空實(shí)現(xiàn)管引。其實(shí)這也很容易理解士败。繪制子View也只有ViewGroup類型的控件才會(huì)有子View,因此在View類中并沒有具體的實(shí)現(xiàn)邏輯。我們?nèi)iewGroup中看看dispatchDraw()方法:
@Override
protected void dispatchDraw(Canvas canvas) {
boolean usingRenderNodeProperties = canvas.isRecordingFor(mRenderNode);
final int childrenCount = mChildrenCount;
final View[] children = mChildren;
int flags = mGroupFlags;
//判斷當(dāng)前ViewGroup容器是否設(shè)置了布局動(dòng)畫褥伴,如果有谅将,那么遍歷所有子View,設(shè)置布局動(dòng)畫
if ((flags & FLAG_RUN_ANIMATION) != 0 && canAnimate()) {
final boolean buildCache = !isHardwareAccelerated();
for (int i = 0; i < childrenCount; i++) {
final View child = children[i];
if ((child.mViewFlags & VISIBILITY_MASK) == VISIBLE) {
final LayoutParams params = child.getLayoutParams();
attachLayoutAnimationParameters(child, params, i, childrenCount);
bindLayoutAnimation(child);
}
}
final LayoutAnimationController controller = mLayoutAnimationController;
if (controller.willOverlap()) {
mGroupFlags |= FLAG_OPTIMIZE_INVALIDATE;
}
//開始布局動(dòng)畫
controller.start();
mGroupFlags &= ~FLAG_RUN_ANIMATION;
mGroupFlags &= ~FLAG_ANIMATION_DONE;
//設(shè)置動(dòng)畫監(jiān)聽
if (mAnimationListener != null) {
mAnimationListener.onAnimationStart(controller.getAnimation());
}
}
int clipSaveCount = 0;
//判斷是否需要裁剪邊緣
final boolean clipToPadding = (flags & CLIP_TO_PADDING_MASK) == CLIP_TO_PADDING_MASK;
if (clipToPadding) {
clipSaveCount = canvas.save();
canvas.clipRect(mScrollX + mPaddingLeft, mScrollY + mPaddingTop,
mScrollX + mRight - mLeft - mPaddingRight,
mScrollY + mBottom - mTop - mPaddingBottom);
}
//遍歷子View,繪制子View
for (int i = 0; i < childrenCount; i++) {
while (transientIndex >= 0 && mTransientIndices.get(transientIndex) == i) {
final View transientChild = mTransientViews.get(transientIndex);
if ((transientChild.mViewFlags & VISIBILITY_MASK) == VISIBLE ||
transientChild.getAnimation() != null) {
//調(diào)用drawChild()方法
more |= drawChild(canvas, transientChild, drawingTime);
}
transientIndex++;
if (transientIndex >= transientCount) {
transientIndex = -1;
}
}
..//其他代碼
}
我們可以看到上面的源碼重慢,大概解釋已經(jīng)在代碼中戏自,其中在遍歷繪制子View的時(shí)候調(diào)用了drawChild()方法,我們進(jìn)去看看:
protected boolean drawChild(Canvas canvas, View child, long drawingTime) {
return child.draw(canvas, this, drawingTime);
}
這里可以看到伤锚,就是調(diào)用了子View的draw()方法。至此就又進(jìn)去了子View的draw()方法志衣,又進(jìn)行我們上面的分析過(guò)程屯援。我們就不再重復(fù)解釋。
整個(gè)繪制的過(guò)程就已經(jīng)基本分析完畢念脯,那么我們來(lái)總結(jié)一下:
最開始ViewRootImpl的performDraw()調(diào)用了ViewRootImpl的draw()方法狞洋,里面調(diào)用了ViewRootImpl的drawSoftware()方法,又調(diào)用了mView的draw()方法(mView就是DecorView,是一個(gè)ViewGroup),draw里面分為4步绿店,繪制背景吉懊,繪制自己,繪制子View,繪制修飾物假勿。其中第二步中onDraw()方法View類中默認(rèn)是空實(shí)現(xiàn)借嗽,所以需要自己實(shí)現(xiàn),第三步中繪制子View的dispatchDraw()方法中View類默認(rèn)為空實(shí)現(xiàn)转培。ViewGroup實(shí)現(xiàn)了它恶导,在里面循環(huán)調(diào)用了所有子View的draw()方法。
View類中onDraw()和dispatchDraw()方法為空實(shí)現(xiàn)浸须,因?yàn)閛nDraw()是需要具體的View繪制自己的UI惨寿,所以不會(huì)提供默認(rèn)實(shí)現(xiàn)。dispatchDraw()也因?yàn)槭荲iewGroup類型的才會(huì)控制繪制子View,所以View類沒有默認(rèn)實(shí)現(xiàn)删窒,只有ViewGroup類才重寫裂垦。
至此我們View的繪制的三個(gè)大流程已經(jīng)基本分析完畢,其中還有很多細(xì)節(jié)的地方?jīng)]有分析到肌索,如果讀者感興趣可以自己探索蕉拢。同時(shí)要感謝網(wǎng)上大神的各種分享資料才弄懂很多東西。