那天,风和日丽,菜鸡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,问题圆满解决了。
经过此次的血泪教训,小张明白了: