Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ViewGroup{TextView,...}.getMeasuredHeight gives wrong value is smaller than real height

Tags:

android

  { January 14, 2011... I have given up to use setListViewHeightBasedOnChildren(ListView listView},
  instead, I don't put my listview in a scrollview, and then just put other contents
  into a listview by using ListView.addHeaderView() and ListView.addFooterView(). 
  http://dewr.egloos.com/5467045 }

ViewGroup(the ViewGroup is containing TextViews having long text except line-feed-character).getMeasuredHeight returns wrong value... that is smaller than real height.

how to get rid of this problem?

here is the java code:

    /*
    I have to set my listview's height by myself. because
    if a listview is in a scrollview then that will be
    as short as the listview's just one item.
    */
    public static void setListViewHeightBasedOnChildren(ListView listView) {
    ListAdapter listAdapter = listView.getAdapter(); 
    if (listAdapter == null) {
        // pre-condition
        return;
    }

    int totalHeight = 0;
    int count = listAdapter.getCount();
    for (int i = 0; i < count; i++) {
        View listItem = listAdapter.getView(i, null, listView);
        listItem.measure(View.MeasureSpec.AT_MOST, View.MeasureSpec.UNSPECIFIED);
        totalHeight += listItem.getMeasuredHeight();
    }

    ViewGroup.LayoutParams params = listView.getLayoutParams();
    params.height = totalHeight + (listView.getDividerHeight() * (listAdapter.getCount() - 1));
    listView.setLayoutParams(params);
}

and here is the list_item_comments.xml:

like image 550
Dewr Avatar asked Jan 12 '11 12:01

Dewr


1 Answers

The question is rather old, but I had similar problem, so I'll describe what was wrong. Actually, parameters in listItem.measure() are used wrong, you should set something like this:

listItem.measure(MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED), MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED))

However, be careful with unspecified width measure spec, it will ignore all layout params and even screen dimensions, so to get correct height, first get maximum width View can use and call measure() this way:

listItem.measure(MeasureSpec.makeMeasureSpec(maxWidth, MeasureSpec.AT_MOST), MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));
like image 106
user711058 Avatar answered Oct 18 '22 17:10

user711058