ScrollView嵌套ListView后,因为滑动事件的冲突,导致listview只能显示一个item的高度,
针对出现的这个问题,有以下两种解决方案:
1.动态设置ListView的高度
public static void setListViewHeightBasedOnChildren(ListViewlistView) {
if(listView == null) return;
ListAdapter listAdapter =listView.getAdapter();
if (listAdapter == null) {
// pre-condition
return;
}
int totalHeight = 0;
for (int i = 0; i < listAdapter.getCount();i++) {
View listItem =listAdapter.getView(i, null, listView);
listItem.measure(0,0);
totalHeight +=listItem.getMeasuredHeight();
}
ViewGroup.LayoutParams params =listView.getLayoutParams();
params.height = totalHeight +(listView.getDividerHeight() * (listAdapter.getCount() - 1));
listView.setLayoutParams(params);
}
上面这个方法就是设定ListView的高度了,在为ListView设置了Adapter之后使用,就可以解决问题了。
但是这个方法有个两个细节需要注意:
一是Adapter中getView方法返回的View的必须由LinearLayout组成,因为只有LinearLayout才有measure()方法,如果使用其他的布局如RelativeLayout,在调用listItem.measure(0, 0);时就会抛异常,因为除LinearLayout外的其他布局的这个方法就是直接抛异常的,没理由…。我最初使用的就是这个方法,但是因为子控件的顶层布局是RelativeLayout,所以一直报错,不得不放弃这个方法。
2.自定义一个Listview
写一个类去继承Listview然后去重写onMeasure方法
protected void onMeasure(int widthMeasureSpec, intheightMeasureSpec) {
int expandSpec =MeasureSpec.makeMeasureSpec(Integer.MAX_VALUE >> 2,
MeasureSpec.AT_MOST);
super.onMeasure(widthMeasureSpec, expandSpec);
}