Determine the height of the ListView before loading the list
Is it possible to determine the height of the ListView before it is displayed on the screen? If my ListView had, say, 3 items, and the height was limited to those 3 items (and the ListView doesn't take up the full screen height), can I determine the height before Android renders the items to the screen?
+3
source to share
2 answers
Use the following method to get and set the height based on the children present
private static void setListViewHeightBasedOnChildren(ListView iListView) {
ListAdapter listAdapter = iListView.getAdapter();
if (listAdapter == null)
return;
int desiredWidth = View.MeasureSpec.makeMeasureSpec(iListView.getWidth(), View.MeasureSpec.UNSPECIFIED);
int totalHeight = 0;
View view = null;
for (int i = 0; i < listAdapter.getCount(); i++) {
view = listAdapter.getView(i, view, iListView);
if (i == 0)
view.setLayoutParams(new ViewGroup.LayoutParams(desiredWidth, RelativeLayout.LayoutParams.WRAP_CONTENT));
view.measure(desiredWidth, View.MeasureSpec.UNSPECIFIED);
totalHeight += view.getMeasuredHeight();
}
ViewGroup.LayoutParams params = iListView.getLayoutParams();
params.height = totalHeight + (iListView.getDividerHeight() * (listAdapter.getCount() - 1));
Log.d("TAG", "ListView Height --- "+params.height);
iListView.setLayoutParams(params);
iListView.requestLayout();
}
+2
source to share