这里我们的ListView不能直接用,要自定义一个,然后重写onMeasure()方法:
原因:如果litview item中Textview文字过多,不重写onMeasure()方法会导致listView总高度达不到预想情况。
自定义ListView重写构造方法及onMeasure()方法
public class MyListView extends ListView {
public MyListView(Context context) {
super(context);
}
public MyListView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public MyListView(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);
}
}
有兴趣的朋友可以看下自定义View之onMeasure()这篇文章。
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++) {
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));
params.height += 5;//if without this statement,the listview will be a little short
listView.setLayoutParams(params);
}
使用起来也是非常方便
mListView.setFocusable(false);
listadapter = new MyListViewAdapter(mListView, getActivity());
mListView.setAdapter(listadapter);
setListViewHeightBasedOnChildren(mJiyouListview);//注意:计算高度必须放在设置适配器以后。