I need to find the height of android ListView with custom ListVAdapter. Each of ListView items can be of varying height. I have tried the following code which I found here:
public static void setListViewHeightBasedOnChildren(ListView listView) {
ListAdapter listAdapter = listView.getAdapter();
if (listAdapter == null) {
return;
}
int totalHeight = 0;
for (int i = 0; i < listAdapter.getCount(); i++) {
View listItem = listAdapter.getView(i, null, listView);
listItem.measure(0, MeasureSpec.UNSPECIFIED);
totalHeight += listItem.getMeasuredHeight();
}
ViewGroup.LayoutParams params = listView.getLayoutParams();
params.height = totalHeight + (listView.getDividerHeight() * (listAdapter.getCount() - 1));
listView.setLayoutParams(params);
listView.requestLayout();
}
But it doesn't give actual height; it gives same height for all list items. Is it possible to find ListView height with list items of varying height?
Based on @jeevamuthu code.
public static int getLVHeight(ListView listView) {
ListAdapter adapter = listView.getAdapter();
int height = 0;
int count = adapter.getCount();
for (int i = 0; i < count; i++) {
View view = adapter.getView(i, null, listView);
view.measure(
View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED),
View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));
height += view.getMeasuredHeight();
}
height += listView.getDividerHeight() * (count - 1);
return height;
}
private int getTotalHeightofListView() {
ListAdapter LvAdapter = lv.getAdapter();
int listviewElementsheight = 0;
for (int i = 0; i < mAdapter.getCount(); i++) {
View mView = mAdapter.getView(i, null, lv);
mView.measure(
MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED),
MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));
listviewElementsheight += mView.getMeasuredHeight();
}
return listviewElementsheight;
}
try this code.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With