today about how to obtain a dynamic listview height. Look at the code:
;
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);
}
Use this code to get listview height, you need to pay attention to several issues:
1, listview the item's root layout must be a LinearLayout;
2, calling this method requires the data loaded in the adapter after the update; codes are as follows:
mAdapter.notifyDataSetChanged (); ; Function.getTotalHeightofListView (mListView);
3, get item highly commented code can also be used, the effect is the same.
Hey its really helpful Thanks a lot
回复删除