项目中,ScrollView嵌套ListView是比较常见的需求,就会导致一个很常见的问题:ListView只显示一行。
解决这个问题,一般有两种方法:
1.动态计算ListView的高度。
2.只需要将你的ListView替换成NoScrollListView 即可。(见下文附NoScrollView)
第一种方法:
public static void setListViewHeightBasedOnChildren(ListView listView) {
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);
listItem.measure(
MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED),
MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));
totalHeight += listItem.getMeasuredHeight();
}
ViewGroup.LayoutParams params = listView.getLayoutParams();
params.height = totalHeight + (listView.getDividerHeight() * (listAdapter.getCount() - 1));
listView.setLayoutParams(params);
}
使用这个方法来获取listview的高度,需要注意一下几个问题:
1、listview的item的根布局一定要是LinearLayout;
2、调用这个方法需要在适配器数据加载更新之后;代码如下:
mAdapter.notifyDataSetChanged();
CommonUtils.setListViewHeightBasedOnChildren(mListView);
第二种方法:
import android.content.Context;
import android.util.AttributeSet;
import android.widget.ListView;
/**
* ScrollView嵌套ListView
* @author wy
*
*/
public class NoScrollListView extends ListView {
public NoScrollListView (Context context, AttributeSet attrs) {
super(context, attrs);
}
public NoScrollListView (Context context) {
super(context);
}
public NoScrollListView (Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
@Override
public void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int expandSpec = MeasureSpec.makeMeasureSpec(
Integer.MAX_VALUE >> 2, MeasureSpec.AT_MOST);
super.onMeasure(widthMeasureSpec, expandSpec);
}
}
网友评论