This question is not solved by these StackOverflow questions
I have ListView in a ScrollView (Yes, I know this is a "bad idea" but the ListView has several niceties that make this approach desirable) and I need to set the height of the listView within the ScrollView.
The code published on stackoverflow works in some cases, and I have used it, however it does not work in this case, which is why I am asking this question again.
My ListView items are a single TextView. However this textview often contains a sentence and therefore wraps. The functions posted so far work only for single-line elements. As soon as they go multiline, it fails to calculate the height correctly.
public static void setListViewHeight(ListView listView)
{
ListAdapter myListAdapter = listView.getAdapter();
if (myListAdapter == null) {
return;
}
int totalHeight = listView.getPaddingTop() + listView.getPaddingBottom();
int adapterCount = myListAdapter.getCount();
for (int i = 0; i < adapterCount ; i++) {
View listItem = myListAdapter.getView(i, null, listView);
listItem.measure(listView.getWidth(), MeasureSpec.UNSPECIFIED);
totalHeight += listItem.getMeasuredHeight();
}
//Change Height of ListView
ViewGroup.LayoutParams params = listView.getLayoutParams();
Drawable d = listView.getDivider();
params.height = (int)(totalHeight) + ((listView.getDividerHeight() +3 ) * (adapterCount - 1));
listView.setLayoutParams(params);
listView.invalidateViews();
listView.requestLayout();
}
I have also tried the over version of this function, same results. The listItem's height is always (in my case) 57, irrespective of the text in it. I am looking for a way to have it properly calculate the height.
Sample height data: "heated door locks" : 57 "dual body-color heated power mirrors w/driver memory/reverse gear activated passenger mirror tilt down": 57 (takes up 3 lines of text)