Android開發(fā)藝術(shù)探索筆記
SpecMode
- UNSPECIFIED,表示一種測量狀態(tài),對View的大小不做限制,要多大給多大。一般用于系統(tǒng)內(nèi)部。
- EXACTLY,父容器已經(jīng)知道View的精確大小,即SpecSize。對應(yīng)于LayoutParams的match_parent。
- AT_MOST,父容器指定了一個(gè)最大的SpecSize,View不能大于該值,View具體的大小要看View的具體實(shí)現(xiàn)。對應(yīng)于LayoutParams的wrap_content。
整體Measure流程
主要是分為MeasureSpec和Measure兩個(gè)過程
- MeasureSpec過程是根據(jù)View自身的LayoutParams和其父控件的MeasureSpec來確定View的MeasureSpec。頂級(jí)父控件DecorView的MeasureSpec由窗口的尺寸和自身的LayoutParams決定。
- Measure過程是根據(jù)View的MeasureSpec來測量的寬/高度(View的最終寬高和四個(gè)頂點(diǎn)的位置在layout結(jié)束后確定)。
MeasureSpec的過程
分為頂層View即DecorView,和普通View(包含ViewGroup)兩種情況:
. DecorView,其MeasureSpec由窗口的尺寸和自身的LayoutParams決定。
. 普通View,其MeasureSpec由父容器的MeasureSpec和自身的LayoutParams共同決定。
- DecorView的MeasureSpec的創(chuàng)建過程
DecorView對應(yīng)的實(shí)現(xiàn)類是ViewRootImpl。MeasureSpec從measureHierarchy方法開始。
先碼上measureHierarchy的所有代碼,看看就好:
if (lp.width == ViewGroup.LayoutParams.WRAP_CONTENT) {
// On large screens, we don't want to allow dialogs to just
// stretch to fill the entire width of the screen to display
// one line of text. First try doing the layout at a smaller
// size to see if it will fit.
final DisplayMetrics packageMetrics = res.getDisplayMetrics();
res.getValue(com.android.internal.R.dimen.config_prefDialogWidth, mTmpValue, true);
int baseSize = 0;
if (mTmpValue.type == TypedValue.TYPE_DIMENSION) {
baseSize = (int)mTmpValue.getDimension(packageMetrics);
}
if (DEBUG_DIALOG) Log.v(TAG, "Window " + mView + ": baseSize=" + baseSize);
if (baseSize != 0 && desiredWindowWidth > baseSize) {
childWidthMeasureSpec = getRootMeasureSpec(baseSize, lp.width);
childHeightMeasureSpec = getRootMeasureSpec(desiredWindowHeight, lp.height);
performMeasure(childWidthMeasureSpec, childHeightMeasureSpec);
if (DEBUG_DIALOG) Log.v(TAG, "Window " + mView + ": measured ("
+ host.getMeasuredWidth() + "," + host.getMeasuredHeight() + ")");
if ((host.getMeasuredWidthAndState()&View.MEASURED_STATE_TOO_SMALL) == 0) {
goodMeasure = true;
} else {
// Didn't fit in that size... try expanding a bit.
baseSize = (baseSize+desiredWindowWidth)/2;
if (DEBUG_DIALOG) Log.v(TAG, "Window " + mView + ": next baseSize="
+ baseSize);
childWidthMeasureSpec = getRootMeasureSpec(baseSize, lp.width);
performMeasure(childWidthMeasureSpec, childHeightMeasureSpec);
if (DEBUG_DIALOG) Log.v(TAG, "Window " + mView + ": measured ("
+ host.getMeasuredWidth() + "," + host.getMeasuredHeight() + ")");
if ((host.getMeasuredWidthAndState()&View.MEASURED_STATE_TOO_SMALL) == 0) {
if (DEBUG_DIALOG) Log.v(TAG, "Good!");
goodMeasure = true;
}
}
}
}
measureHierarchy()中的參數(shù):desiredWindowWidth窗口的寬 ;desiredWindowHeight窗口的高
measureHierarchy會(huì)處理WRAP_CONTENT時(shí)的大屏的特殊情況,見如下的注釋
if (lp.width == ViewGroup.LayoutParams.WRAP_CONTENT) {
// On large screens, we don't want to allow dialogs to just
// stretch to fill the entire width of the screen to display
// one line of text. First try doing the layout at a smaller
// size to see if it will fit.
measureHierarchy中大部分代碼都是用來處理這個(gè)邏輯的。剩下關(guān)于MeasureSpec的代碼只有短短三行。
childWidthMeasureSpec = getRootMeasureSpec(baseSize, lp.width);
childHeightMeasureSpec = getRootMeasureSpec(desiredWindowHeight, lp.height);
performMeasure(childWidthMeasureSpec, childHeightMeasureSpec);
MeasureSpec的邏輯重點(diǎn)自然在getRootMeasureSpec()方法中。其注釋就直白的說明了
/**
* Figures out the measure spec for the root view in a window based on it's
* layout params.
* 根據(jù)root view的 layout params確定其measure spec
* @param windowSize
* The available width or height of the window
*
* @param rootDimension
* The layout params for one dimension (width or height) of the
* window.
*
* @return The measure spec to use to measure the root view.
*/
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.
//對應(yīng)MeasureSpec.EXACTLY的精確模式,大小為窗口大小。
measureSpec = MeasureSpec.makeMeasureSpec(windowSize, MeasureSpec.EXACTLY);
break;
case ViewGroup.LayoutParams.WRAP_CONTENT:
// Window can resize. Set max size for root view.
//對應(yīng)MeasureSpec.AT_MOST的最大模式,大小不能超過窗口大小。
measureSpec = MeasureSpec.makeMeasureSpec(windowSize, MeasureSpec.AT_MOST);
break;
default:
// Window wants to be an exact size. Force root view to be that size.
//對應(yīng)MeasureSpec.EXACTLY的精確模式,大小為布局中的指定大小
measureSpec = MeasureSpec.makeMeasureSpec(rootDimension, MeasureSpec.EXACTLY);
break;
}
return measureSpec;
}
- 普通View的MeasureSpec的創(chuàng)建過程
View的measure的ViewGroup的measureChildWithMargins開始
/**
* Ask one of the children of this view to measure itself, taking into
* account both the MeasureSpec requirements for this view and its padding
* and margins. The child must have MarginLayoutParams The heavy lifting is
* done in getChildMeasureSpec.
*
* @param child The child to measure
* @param parentWidthMeasureSpec The width requirements for this view
* @param widthUsed Extra space that has been used up by the parent
* horizontally (possibly by other children of the parent)
* @param parentHeightMeasureSpec The height requirements for this view
* @param heightUsed Extra space that has been used up by the parent
* vertically (possibly by other children of the parent)
*/
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);
}
又上面代碼可以看出MeasureSpec的邏輯代碼自然是在getChildMeasureSpec()中。也可以看出,在確定好MeasureSpec后,就開始了child的measure流程
child.measure(childWidthMeasureSpec, childHeightMeasureSpec);
下面看getChildMeasureSpec的具體邏輯
/**
* Does the hard part of measureChildren: figuring out the MeasureSpec to
* pass to a particular child. This method figures out the right MeasureSpec
* for one dimension (height or width) of one child view.
*
* The goal is to combine information from our MeasureSpec with the
* LayoutParams of the child to get the best possible results. For example,
* if the this view knows its size (because its MeasureSpec has a mode of
* EXACTLY), and the child has indicated in its LayoutParams that it wants
* to be the same size as the parent, the parent should ask the child to
* layout given an exact size.
*
* @param spec The requirements for this view
* @param padding The padding of this view for the current dimension and
* margins, if applicable
* @param childDimension How big the child wants to be in the current
* dimension
* @return a MeasureSpec integer for the child
*/
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);
//首先說下padding參數(shù),以寬度為例。由measureChildWithMargins方法看出,該參數(shù)是將ViewGroup的
//左右padding,view自身的左右margin以及ViewGroup中已經(jīng)被占用的寬度。由此可以看出,
//無論view怎樣,其寬度都不能超過lp.width - padding
int resultSize = 0;
int resultMode = 0;
switch (specMode) {
// Parent has imposed an exact size on us
case MeasureSpec.EXACTLY: //父控件為精確模式EXACTLY時(shí)
if (childDimension >= 0) { //1. 1View布局中為具體大小值
resultSize = childDimension; // view為EXACTLY,大小為布局中指定的值
resultMode = MeasureSpec.EXACTLY;
} else if (childDimension == LayoutParams.MATCH_PARENT) { //1.2 View為MATCH_PARENT
// Child wants to be our size. So be it.
resultSize = size; //View可以精確到和父控件一樣大,所以View為EXACTLY模式
resultMode = MeasureSpec.EXACTLY; //大小為父控件可用的大?。ǔ袅藀adding)
} else if (childDimension == LayoutParams.WRAP_CONTENT) { //1.3 View為WRAP_CONTENT
// Child wants to determine its own size. It can't be
// bigger than us. //此時(shí)View大小隨內(nèi)容變化,但不能超過父控件的可用空間
resultSize = size; //所以View為AT_MOST最大模式
resultMode = MeasureSpec.AT_MOST; //大小為父控件可用的大?。ǔ袅藀adding)
}
break;
// Parent has imposed a maximum size on us
case MeasureSpec.AT_MOST: //父控件為AT_MOST最大模式
if (childDimension >= 0) { //2.1 View布局中為具體大小值
// Child wants a specific size... so be it
resultSize = childDimension; // view為EXACTLY,大小為布局中指定的值
resultMode = MeasureSpec.EXACTLY;
} else if (childDimension == LayoutParams.MATCH_PARENT) {//2.2View為MATCH_PARENT
// Child wants to be our size, but our size is not fixed.
// Constrain child to not be bigger than us.
resultSize = size; //View大小和父控件一樣,不能超過父控件的最大值
resultMode = MeasureSpec.AT_MOST; //View為最大模式,大小不能超過父控件的可用空間
} else if (childDimension == LayoutParams.WRAP_CONTENT) {//2.3 View為WRAP_CONTENT
// Child wants to determine its own size. It can't be
// bigger than us. //View大小隨內(nèi)容變化,打不能超過超過父控件的可用空間
resultSize = size; //所以View為AT_MOST最大模式
resultMode = MeasureSpec.AT_MOST; //大小為父控件可用的大小(除掉了padding)
}
break;
// Parent asked to see how big we want to be
case MeasureSpec.UNSPECIFIED: //父控件為UNSPECIFIED未指定模式
if (childDimension >= 0) { //3.1View布局中為具體大小值
// Child wants a specific size... let him have it
resultSize = childDimension;
resultMode = MeasureSpec.EXACTLY; // view為EXACTLY,大小為布局中指定的值
} else if (childDimension == LayoutParams.MATCH_PARENT) {//3.2View為MATCH_PARENT
// Child wants to be our size... find out how big it should
// be
resultSize = View.sUseZeroUnspecifiedMeasureSpec ? 0 : size;
resultMode = MeasureSpec.UNSPECIFIED; //View也為UNSPECIFIED,大小為0
} else if (childDimension == LayoutParams.WRAP_CONTENT) {//3.3View為WRAP_CONTENT
// Child wants to determine its own size.... find out how
// big it should be
resultSize = View.sUseZeroUnspecifiedMeasureSpec ? 0 : size;
resultMode = MeasureSpec.UNSPECIFIED;//View也為UNSPECIFIED,大小為0
}
break;
}
return MeasureSpec.makeMeasureSpec(resultSize, resultMode);
}
measure流程
分為View的measure過程和ViewGroup的measure過程。
- View的measure過程
ViewGroup在measureChildWithMargins中確定了View的MeasureSpec后調(diào)用
child.measure(childWidthMeasureSpec, childHeightMeasureSpec);
View的measure方法是個(gè)final方法,但其中會(huì)調(diào)用onMeasure();
public final void measure(int widthMeasureSpec, int heightMeasureSpec) {
...
if (cacheIndex < 0 || sIgnoreMeasureCache) {
// measure ourselves, this should set the measured dimension flag back
onMeasure(widthMeasureSpec, heightMeasureSpec);
mPrivateFlags3 &= ~PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT;
}
...
}
View的onMeasure方法如下:
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
setMeasuredDimension(getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec),
getDefaultSize(getSuggestedMinimumHeight(), heightMeasureSpec));
}
setMeasuredDimension()方法會(huì)設(shè)置View的寬高,如果我們在重寫onMeasure時(shí),也一定要該方法,是寬高生效。
默認(rè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;
}
邏輯很簡單MeasureSpec.AT_MOST和 MeasureSpec.EXACTLY模式時(shí),View的大小即specSize。
MeasureSpec.UNSPECIFIED時(shí)View的大小為第一個(gè)參數(shù)(以寬為例),即onMeasure傳過來的getSuggestedMinimumWidth。
protected int getSuggestedMinimumWidth() {
return (mBackground == null) ? mMinWidth : max(mMinWidth, mBackground.getMinimumWidth());
}
這里的邏輯是,如果View沒有設(shè)置背景,則去mMinWidth,對應(yīng)的是android:minWidth設(shè)置的值;如果View設(shè)置了背景,怎取背景的getMinimumWidth()值和minWidth中大的那個(gè).
背景的getMinimumWidth()也很簡單,即有原始寬高時(shí)取原始寬高,沒有取0.
public int getMinimumWidth() {
final int intrinsicWidth = getIntrinsicWidth();
return intrinsicWidth > 0 ? intrinsicWidth : 0;
}
總結(jié),View的測量問題在于:View在WRAP_CONTENT時(shí),其最終的模式時(shí)AT_MOST,且大小是父控件的可用大小。這和MATCH_PARENT時(shí)沒有區(qū)別。因此在自定義View時(shí),我們要處理View在WRAP_CONTENT時(shí)的這一問題。
- ViewGroup的measure過程
ViewGroup比較簡單,它的measure流程和View一樣,作為其父控件的子View處理,不同的是,ViewGroup沒有重寫onMeasure方法,而是交給其子類去按需實(shí)現(xiàn)。
以LinearLayout為例。LinearLayout會(huì)遍歷子View,一次調(diào)用子View的measure方法,并紀(jì)錄每個(gè)子View的測量值,最后再測量自己的大小。
獲取View的寬高
因?yàn)锳ctivity的生命周期和View的測量是異步的,所以并不能在Activity的生命周期函數(shù)中直接獲取。通??梢酝ㄟ^以下幾種方式獲?。?/p>
- onWindowsFocusChanged
這個(gè)回調(diào)函數(shù)在View初始化完成后調(diào)用,所以在這里獲取寬高可以確保是View測量后的寬高。需要注意的是,該函數(shù)在Activity失去和獲取焦點(diǎn)的時(shí)候都會(huì)觸發(fā)。
public void onWindowsFocusChanged(boolean hasFocus){
super.onWindowsFocusChanged(hasFocus);
if (hasFocus) {
int width = view.getMeasureWidth();
int herght = view.getMeasureHeight();
}
}
- view.post(runnable)
此方法通過post將一個(gè)runnable投遞到消息隊(duì)列的尾部,因?yàn)樵谖膊浚源藃unnable被Looper處理時(shí),View已經(jīng)測量完成了。
protected void omStart(){
super.omStart();
view.post(new Runnable(){
@override
public void run(){
int width = view.getMeasureWidth();
int herght = view.getMeasureHeight();
}
});
}
- ViewTreeObserverd的OnGlobalLayoutListener接口
OnGlobalLayoutListener中的onGlobalLayout方法會(huì)在View樹的狀態(tài)發(fā)生變化時(shí)回調(diào)。注意,此方法回多次調(diào)用
protected void onStart(){
super.onStart();
ViewTreeOberver observer = view.getViewTreeObserver();
observer.addOnGlobalLayoutListener(new OnGlobalLayoutListener(){
@Override
public void onGlobalLayout() {
view.getViewTreeObserver().removeGlobalOnLayoutListener(this);
int width = view.getMeasureWidth();
int herght = view.getMeasureHeight();
}
}
)
}
4.view.measure(int widthMeasureSpec , int heightMeasureSpec)
手動(dòng)觸發(fā)測量