那天,風和日麗,菜雞Android開發工程師小張開心的寫着 bug 代碼 ,忽然,測試經理老石跑過來講客戶報上來一個線上bug,小張忽然菊花一緊,說不可能,個人代碼是不可能有問題的。而後老石從胯下 口袋 掏出來手機,三下五除二將bug復現出來了:android
從圖中咱們明顯能看到,底部的服務彈框被裁切擋住了,顯示的不完整。bash
看到復原的犯罪現場,小張內心一個放鬆:「還好還好,不是我寫的代碼。」當着老石的面,小張認可是代碼出了問題,答應了老石下個版本修復,老石纔不依不撓的走開了。打發走了老石,小張開始分析起來問題了。開始,小張簡單的認爲是底部的彈框(Dialog)的高度過小了,形成了dialog的內容顯示不完整。然鵝,看到出問題的代碼,小張開始發現事情並不簡單,涉事代碼以下:app
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<!-- 省略無關代碼 -->
<com.xx.ListViewForScrollView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginLeft="20dp"
android:layout_marginTop="18dip"
android:layout_marginRight="20dp"
android:layout_marginBottom="48dp"
android:divider="@null">
</com.xx.ListViewForScrollView>
</RelativeLayout>
複製代碼
看到上面Dialog的佈局xml文件中的ListViewForScrollView小張內心不由泛起了嘀咕:「怎麼又是自定義的View,又要看一大堆邏輯了,腦袋疼,腦袋疼...」轉念一想,不對啊,這個View看名字一看就是繼承自ListView
,就算是Dialog的高度不夠,這個ListViewForScrollView
也應該能滑動纔對啊,如今不能滑動了是怎麼一回事,有問題有問題...less
不看代碼光靠猜是解決不了問題的,小張下定決心去研究研究這個自定義View,打開這個ListViewForScrollView
的代碼,小張鬆了一口氣:還好還好,代碼量並很少,看起來邏輯並不複雜:ide
public class ListViewForScrollView extends ListView {
public ListViewForScrollView(Context context) {
super(context);
}
public ListViewForScrollView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public ListViewForScrollView(Context context, AttributeSet attrs,
int defStyle) {
super(context, attrs, defStyle);
}
@Override
/**
* 重寫該方法,達到使ListView適應ScrollView的效果
*/
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int expandSpec = MeasureSpec.makeMeasureSpec(Integer.MAX_VALUE >> 2,
MeasureSpec.AT_MOST);
super.onMeasure(widthMeasureSpec, expandSpec);
}
}
複製代碼
看到這段代碼,小張更疑惑了:「這不就是繼承的ListView麼,也沒什麼特殊的邏輯啊,爲啥它就是不能滑動呢?」
爲了解決內心的疑惑,小張決定從這個ListViewForScrollView惟一重寫的方法onMeasure(int widthMeasureSpec, int heightMeasureSpec)
下手,看能不能發現問題。
剛開始看第一段代碼,小張就犯難了,這個MeasureSpec
是個什麼東東?看起來不理解這個MeasureSpec
是解決不了問題了,小張決定了解一下這個MeasureSpec:佈局
咱們都知道,View展現在手機上,須要經歷測量-繪製-佈局三個流程,對應到View的代碼中就是onMeasure()
、onDraw()
、onLayout()
三個方法。在onMeasure()過程當中,咱們就須要藉助MeasureSpec對View進行測量。
onMeasure()方法接受兩個參數:widthMeasureSpec
和heightMeasureSpec
,這兩個參數都是32位的int類型,由View的父控件傳過來。重點來了:View的onMeasure()方法,實際上是由父控件調用,那View的大小難道就只能有父控件決定麼?其實否則。咱們剛纔也說了,widthMeasureSpec和heightMeasureSpec都是32位的int類型,他們的高兩位表示測量模式mode,低30位表示測量大小size。經過MeasureSpec這個靜態類,咱們很容易獲取View的測量模式和測量大小,其中測量模式有3種:測試
UNSPECIFIED
父控件不對你有任何限制,你想要多大給你多大,想上天就上天。這種狀況通常用於系統內部,表示一種測量狀態。(這個模式主要用於系統內部屢次Measure的情形,並非真的說你想要多大最後就真有多大)ui
EXACTLY
父控件已經知道你所需的精確大小,你的最終大小應該就是這麼大。this
AT_MOST
你的大小不能大於父控件給你指定的size,但具體是多少,得看你本身的實現。spa
父控件經過ViewGroup中的靜態方法getChildMeasureSpec來獲取子控件的測量規格。下面是getChildMeasureSpec()的代碼(因爲小張terrible的英語水平,就不給你們翻譯註釋了,你們能夠自行有道~):
/**
* 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);
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);
}
複製代碼
該方法經過將父控件的測量規格和childview的佈局參數LayoutParams
相結合,獲得一個最可能符合條件的child view的測量規格。
經過以上代碼,你們能夠有一個概念:就是一個View的大小是由它的父控件加上自身的LayoutParams決定的。詳情以下(圖片來源於任玉剛博客):
經過了解View的Measure過程,小張知道了,在ListViewForScrollView的onMeasure()方法裏,強行將ListView的測量模式改成了AT_MOST,並將測量大小改成了MAX_VALUE >> 2,接着調用父類ListView的onMeasure()方法,咱們來看看ListView的onMeasure()方法:
/** 源碼來自8.0.0_r4,不一樣版本可能略有不一樣 **/
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
/** 此處省略不相關代碼 **/
//......
// 測量模式爲AT_MOST,測量大小爲MAX_VALUE >> 2,也就是536870911
if (heightMode == MeasureSpec.AT_MOST) {
heightSize = measureHeightOfChildren(widthMeasureSpec, 0, NO_POSITION, heightSize, -1);
}
setMeasuredDimension(widthSize, heightSize);
/** 繼續省略 **/
//......
}
複製代碼
經過上面的代碼咱們能夠看到,最終這個自定義的ListViewForScrollView的高度是由measureHeightOfChildren
這個方法肯定的,小張接着查看這個方法:
/**
* Measures the height of the given range of children (inclusive) and
* returns the height with this ListView's padding and divider heights * included. If maxHeight is provided, the measuring will stop when the * current height reaches maxHeight. * * @param widthMeasureSpec The width measure spec to be given to a child's
* {@link View#measure(int, int)}.
* @param startPosition The position of the first child to be shown.
* @param endPosition The (inclusive) position of the last child to be
* shown. Specify {@link #NO_POSITION} if the last child should be
* the last available child from the adapter.
* @param maxHeight The maximum height that will be returned (if all the
* children don't fit in this value, this value will be * returned). * @param disallowPartialChildPosition In general, whether the returned * height should only contain entire children. This is more * powerful--it is the first inclusive position at which partial * children will not be allowed. Example: it looks nice to have * at least 3 completely visible children, and in portrait this * will most likely fit; but in landscape there could be times * when even 2 children can not be completely shown, so a value * of 2 (remember, inclusive) would be good (assuming * startPosition is 0). * @return The height of this ListView with the given children. */ final int measureHeightOfChildren(int widthMeasureSpec, int startPosition, int endPosition, int maxHeight, int disallowPartialChildPosition) { final ListAdapter adapter = mAdapter; if (adapter == null) { return mListPadding.top + mListPadding.bottom; } // Include the padding of the list int returnedHeight = mListPadding.top + mListPadding.bottom; final int dividerHeight = mDividerHeight; // The previous height value that was less than maxHeight and contained // no partial children int prevHeightWithoutPartialChild = 0; int i; View child; // mItemCount - 1 since endPosition parameter is inclusive endPosition = (endPosition == NO_POSITION) ? adapter.getCount() - 1 : endPosition; final AbsListView.RecycleBin recycleBin = mRecycler; final boolean recyle = recycleOnMeasure(); final boolean[] isScrap = mIsScrap; for (i = startPosition; i <= endPosition; ++i) { child = obtainView(i, isScrap); measureScrapChild(child, i, widthMeasureSpec, maxHeight); if (i > 0) { // Count the divider for all but one child returnedHeight += dividerHeight; } // Recycle the view before we possibly return from the method if (recyle && recycleBin.shouldRecycleViewType( ((LayoutParams) child.getLayoutParams()).viewType)) { recycleBin.addScrapView(child, -1); } returnedHeight += child.getMeasuredHeight(); if (returnedHeight >= maxHeight) { // We went over, figure out which height to return. If returnedHeight > maxHeight, // then the i'th position did not fit completely.
return (disallowPartialChildPosition >= 0) // Disallowing is enabled (> -1)
&& (i > disallowPartialChildPosition) // We've past the min pos && (prevHeightWithoutPartialChild > 0) // We have a prev height && (returnedHeight != maxHeight) // i'th child did not fit completely
? prevHeightWithoutPartialChild
: maxHeight;
}
if ((disallowPartialChildPosition >= 0) && (i >= disallowPartialChildPosition)) {
prevHeightWithoutPartialChild = returnedHeight;
}
}
// At this point, we went through the range of children, and they each
// completely fit, so return the returnedHeight
return returnedHeight;
}
複製代碼
經過查看該方法,小張知道了這個方法的意義就是測量給定範圍的高度,並返回包含此ListView的填充和分隔符高度的高度。若是提供了maxHeight,噹噹前高度達到maxHeight時,測量將中止。而對於ListViewForScrollView,maxHeight就是上面onMeasure()中咱們傳過來的536870911(即MAX_VALUE >> 2)
,若是ListView的itemView的總高度不超過這個值,那麼ListView的高度就是全部itemView高度加上分隔符加上padding的高度,不然就爲536870911。因此問題的緣由就很清楚了,ListViewForScrollView的高度在大多數狀況下都爲咱們指定的536870911,而這種狀況下ListView是不能滑動的。
經過研究ListViewForScrollView,小張發現這個自定義View是用來解決ScrollView嵌套ListView帶來的滑動衝突等問題的,而出問題的Dialog根佈局是RelativeLayout,並非ScrollView,因此小張將佈局文件中的ListViewForScrollView換成了ListView,問題圓滿解決了。
經過此次的血淚教訓,小張明白了: