记录下scrollview嵌套listview时的小坑
2017-01-14 本文已影响0人
茶And狗狗
1、解决scrollview嵌套listview时,默认显示最下面的问题:调用listView.setFocusable(false);
2、解决scrollview嵌套listview时,listview只显示一行的问题:
方法1:
先定义一个方法:
/**
* 动态设置listview高度的方法,主要针对scrollView套listview的只显示一行的bug
* @param listView
*/
public static void setListViewHeightBasedOnChildren(ListView listView) {
ListAdapter listAdapter = listView.getAdapter();
if (listAdapter == null) {
return;
}
int totalHeight = 0;
for (int i = 0; i < listAdapter.getCount(); i += 1) {
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);
}
然后调用这个方法setListViewHeightBasedOnChildren(listView);把listview传进去就好了。
方法2:
自定义一个listview继承ListView,重写onMeasure()方法,:
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec){
int newHeightMeasureSpec = MeasureSpec.makeMeasureSpec(Integer.MAX_VALUE>>2,MeasureSpec.AT_MOST);
super.onMeasure(widthMeasureSpec, newHeightMeasureSpec);
}
然后直接在scrollview中使用自定义的这个listView就好了