android ListView是非常常用的界面布局控件,非常好用。
ListView与ListAdapter配合,创建可以滑动的列表。构成了一种开发模式(貌似叫做 适配器 模式)。
本人最喜欢的做法就是 写一个类继承 BaseAdapter,关键实现 getView() 方法。
getView()方法有时候需要加载布局文件,设置界面内容,总的来说这是ListView显示过程中比较耗时的。
为了让ListView更加高效,最好让getView()调用的次数尽可能少。
然而,很多情况下(MeasureSpec.AT_MOST),ListView为了确认自己的高度(onMeasure),需要通过调用getView()方法来获取每个子View( child )的高度。这样一来,仅仅为了获得子View的高度而调用getView()方法,明显做了很多无用功。而且,大多数情况下,我们的界面的每一条子View高度都是一致的。所以,其实子View的高度只需要算一次!
下面的代码,也就是为了实现这个算法。
自己计算子View( child view ) 的高度,而不是每次调用getView()方法来获得。
class MeasureListView extends ListView { private final int mChildLayoutHeight; public MeasureListView(Context context, int childLayoutId) { super(context); mChildLayoutHeight = getChildMeasureHeight(childLayoutId); } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { int heightMode = MeasureSpec.getMode(heightMeasureSpec); if (heightMode == MeasureSpec.AT_MOST) { // AT_MOST >> EXACTLY super.onMeasure(widthMeasureSpec, getChildrenMeasureHeightSpec(heightMeasureSpec)); } else { super.onMeasure(widthMeasureSpec, heightMeasureSpec); } } private int getChildrenMeasureHeightSpec(int heightMeasureSpec) { if (mChildLayoutHeight == 0) { return MeasureSpec.makeMeasureSpec(0, MeasureSpec.EXACTLY); } else { final int itemCount = getAdapter().getCount(); final int itemHeight = mChildLayoutHeight; final int dividerHeight = ((getDividerHeight() > 0) && getDivider() != null) ? getDividerHeight() : 0; int allHeigth = getListPaddingTop() + getListPaddingBottom(); allHeigth += (dividerHeight * itemCount);// all divider allHeigth += (itemHeight * itemCount);// all children int maxHeight = MeasureSpec.getSize(heightMeasureSpec); if (allHeigth > maxHeight) { allHeigth = maxHeight; } return MeasureSpec.makeMeasureSpec(allHeigth, MeasureSpec.EXACTLY); } } private int getChildMeasureHeight(int childLayoutId) { LayoutInflater inflater = LayoutInflater.from(getContext()); View child = inflater.inflate(childLayoutId, null); if (child == null) { return 0; } LayoutParams p = (LayoutParams) child.getLayoutParams(); if (p == null) { p = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT); child.setLayoutParams(p); } int heightSpec; if (p.height > 0) { heightSpec = MeasureSpec.makeMeasureSpec(p.height, MeasureSpec.EXACTLY); } else { heightSpec = MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED); } child.measure(0, heightSpec);// we don't care the width spec return child.getMeasuredHeight(); } }