Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
393 views
in Technique[技术] by (71.8m points)

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

  { 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:

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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));

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...