1

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)

Community
  • 1
  • 1
user9170
  • 950
  • 9
  • 18
  • 1
    This is probably not what you wanna hear, but there is no reason in the world to put a ListView into a ScrollView! It seems that you want to set the ListView height to the total height of all its items. Just use a LinearLayout in that case and you won't have the problem anymore that you need to calculate the items height. – SimonSays Jun 25 '14 at 22:38
  • Yes, as @SimonSays says, you should not put a ListView into ScrollView. You can find more details [here](http://youtu.be/wDBM6wVEO70?t=42m43s) – GVillani82 Jun 25 '14 at 22:48
  • There are plenty of reasons to put a ListView in a ScrollView. 1. Complicated Adapter Views 2. Item management of the item array 3. Automatic dividers -- there's three good reasons off the top of my head. – user9170 Jun 26 '14 at 13:53

0 Answers0