Android 动态获取ListView的高度
今天介绍一下怎么动态的获取listview的高度。看代码:
public static void getTotalHeightofListView(ListView listView) {
ListAdapter mAdapter = listView.getAdapter();
if (mAdapter == null) {
return;
}
int totalHeight = 0;
for (int i = 0; i < mAdapter.getCount(); i++) {
View mView = mAdapter.getView(i, null, listView);
mView.measure(
MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED),
MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));
//mView.measure(0, 0);
totalHeight += mView.getMeasuredHeight();
Log.w("HEIGHT" + i, String.valueOf(totalHeight));
}
ViewGroup.LayoutParams params = listView.getLayoutParams();
params.height = totalHeight + (listView.getDividerHeight() * (mAdapter.getCount() - 1));
listView.setLayoutParams(params);
listView.requestLayout();
}
使用这个代码来获取listview的高度,需要注意一下几个问题:
1、listview的item的根布局一定要是LinearLayout;
2、调用这个方法需要在适配器数据加载更新之后;代码如下:
mAdapter.notifyDataSetChanged();
Function.getTotalHeightofListView(mListView);
3、获取item的高度也可以用注释掉的代码,效果一样的。
转自:http://blog.sina.com.cn/s/blog_a6a7c2210101b0k7.html
浙公网安备 33010602011771号