scrollview里面嵌套listview的坑

scrollview里面嵌套listview是一种很不好的做法,最好还是使用一个listview,将其他需要滑动的部分添加为头布局脚部局,或者在adapter里面将头脚用一个标志位去判断作为单独的item,这样性能是最完好的,不容易出现bug。

当然了,难免有人会用到的,会出现只显示一个item的bug,解决办法有两种。一种是自定义一个WrapContentListview,很简单的继承自Listview,只需要重写OnMeasure方法

public class WrapContentListView extends ListView{
public WrapContentListView(Context context) {
super(context);
}

public WrapContentListView(Context context, AttributeSet attrs) {
super(context, attrs);
}

public WrapContentListView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}


@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int expandSpec = MeasureSpec.makeMeasureSpec(Integer.MAX_VALUE >> 2,MeasureSpec.AT_MOST);
super.onMeasure(widthMeasureSpec, expandSpec);
}
}
改成这样就好了。
第二种解决办法:动态设置listview,去测量每个item的高度,通过for循环去叠加计算listview的总高度
/**
* 解决ScrollView嵌套ListView只显示一条的问题
* @param listView
*/
public void setListViewHeightBasedOnChildren(ListView listView) {
// 获取ListView对应的Adapter
ListAdapter listAdapter = listView.getAdapter();
if (listAdapter == null) {
return;
}
int totalHeight = 0;
for (int i = 0, len = listAdapter.getCount(); i < len; i++) {
// listAdapter.getCount()返回数据项的数目
View listItem = listAdapter.getView(i,null, listView);
// 计算子项View 的宽高
listItem.measure(0, 0);
// 统计所有子项的总高度
totalHeight += listItem.getMeasuredHeight();
}
ViewGroup.LayoutParams params = listView.getLayoutParams();
params.height = totalHeight + (listView.getDividerHeight() *
(listAdapter.getCount() - 1));
// listView.getDividerHeight()获取子项间分隔符占用的高度
// params.height最后得到整个ListView完整显示需要的高度
listView.setLayoutParams(params);
listView.invalidate();
}

注意:我在项目中遇到这两个都用不了的情况,具体原因是我的item用的是百分比布局或者是wrapcontent那种,所以叠加的时候发生异常就不会动态计算出高度了
我们所需要做的就是把item中高度设为具体的dp值,这样才可以使用以上两种方法。


原文地址:https://www.cnblogs.com/cherrylv/p/6210010.html