网上也有很多例子,简单总结下项目中遇到的情况
1 如果Listview的Item高度是固定的,也就是说,每一个listItem的高度都是一模一样的,那么有如下计算方法
public int setListViewHeightBasedOnChildren(ListView listView) {
ListAdapter listAdapter = listView.getAdapter();
if (listAdapter == null) {
return 0;
}
int totalHeight = 0;
System.out.println("listAdapter.getCount(): " + listAdapter.getCount());
for (int i = 0; i < listAdapter.getCount(); i++) {
View listItem = listAdapter.getView(i, null, listView);
listItem.measure(0, 0);
totalHeight += listItem.getMeasuredHeight();
System.out.println("listView.totalHeight: " + totalHeight + " listItem.getMeasuredHeight(): " + listItem.getMeasuredHeight());
}
ViewGroup.LayoutParams params = listView.getLayoutParams();
System.out.println("listView.getDividerHeight(): " + listView.getDividerHeight());
params.height = totalHeight + (listView.getDividerHeight() * (listAdapter.getCount() - 1));
return params.height;
}
这个方法有一个坏处就是每次都会多执行一遍Adapter中的getView函数,效率不高,优化如下(也是针对固定listitem的高度):
public void setListViewHeight() {
try {
ListAdapter listAdapter = commentListView.getAdapter();
if (listAdapter == null) {
return ;
}
int totalHeight = 0;
int count = listAdapter.getCount();
DebugUtils.printInfo(TAG, "listAdapter.getCount(): " + count);
View listItem = listAdapter.getView(0, null, commentListView);
listItem.measure(0, 0);
int height = listItem.getMeasuredHeight();
totalHeight = count * height;
ViewGroup.LayoutParams params = commentListView.getLayoutParams();
DebugUtils.printInfo(TAG, "listView.getDividerHeight(): " + commentListView.getDividerHeight());
params.height = totalHeight + (commentListView.getDividerHeight() * (count - 1));
DebugUtils.printInfo(TAG, "初始化时listviewParams.height" + params.height);
commentListView.setLayoutParams(params);
} catch (Exception e) {
e.printStackTrace();
}
}
2 如果Listview的Item高度是动态的,例如包含Textview并且超过一行的情况下,如果继续用以上两种方法,那么计算的只是一行TextView的高度
所以这里给了一个很简单的方法,如下:
// 动态改变listView的高度 ,解决TextView超过一行,高度只计算一行的问题
public int setListViewHeightBasedOnChildren(ListView listView) {
ListAdapter listAdapter = listView.getAdapter();
if (listAdapter == null) {
return 0;
}
int totalHeight = 0;
int listViewWidth = ConstValue.screenWidth - Tool.convertDpToPx(this, 12);//listView在布局时的宽度 ,screenWidth - 左右的padding - 左右的margin
int widthSpec = View.MeasureSpec.makeMeasureSpec(listViewWidth, View.MeasureSpec.AT_MOST);
for (int i = 0; i < listAdapter.getCount(); i++) {
View listItem = listAdapter.getView(i, null, listView);
listItem.measure(widthSpec, 0);
int itemHeight = listItem.getMeasuredHeight();
totalHeight += itemHeight;
System.out.println("listView.totalHeight: " + totalHeight + " itemHeight: " + itemHeight);
}
int historyHeight = totalHeight + (listView.getDividerHeight() * listAdapter.getCount() - 1);
System.out.println("listViewHeight = " + historyHeight);
return historyHeight;
}
这个方法没法优化了,本来就不是固定的高度。