定义一个函数将dp转换为像素
public int Dp2Px(Context context, float dp) {
final float scale = context.getResources().getDisplayMetrics().density;
return (int) (dp * scale + 0.5f);
}
定义函数动态控制listView的高度
public void setListViewHeightBasedOnChildren(ListView listView) {
//获取listview的适配器
ListAdapter listAdapter = listView.getAdapter(); //item的高度
if (listAdapter == null) {
return;
}
int totalHeight = 0;
for (int i = 0; i < listAdapter.getCount(); i++) {
View listItem = mAdapter.getView(i, null, listView);
listItem.measure(0, 0); //计算子项View 的宽高 //统计所有子项的总高度
totalHeight += Dp2Px(getApplicationContext(),listItem.getMeasuredHeight())+listView.getDividerHeight();
}
ViewGroup.LayoutParams params = listView.getLayoutParams();
params.height = totalHeight; listView.setLayoutParams(params);
}
在每次listView的adapter发生变化后,要调用setListViewHeightBasedOnChildren(listView)更新界面
原文地址:http://blog.csdn.net/gyz413977349/article/details/42640853