ViewGroup {TextView,...}.getMeasuredHeight给出的错误值小于实际高度

Dew*_*ewr 9 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 }
Run Code Online (Sandbox Code Playgroud)

ViewGroup(ViewGroup包含具有除line-feed-character之外的长文本的TextView).getMeasuredHeight返回错误的值...小于实际高度.

如何摆脱这个问题?

这是java代码:

    /*
    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);
}
Run Code Online (Sandbox Code Playgroud)

这是list_item_comments.xml:

use*_*058 15

问题相当陈旧,但我有类似的问题,所以我会描述错误.实际上,listItem.measure()中的参数使用错误,你应该设置如下:

listItem.measure(MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED), MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED))
Run Code Online (Sandbox Code Playgroud)

但是,要小心未指定的宽度测量规范,它将忽略所有布局参数甚至屏幕尺寸,因此要获得正确的高度,首先获得最大宽度View可以使用并调用measure()这样:

listItem.measure(MeasureSpec.makeMeasureSpec(maxWidth, MeasureSpec.AT_MOST), MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));
Run Code Online (Sandbox Code Playgroud)

  • @ user711058我有同样的问题,但这个解决方案对我不起作用 (2认同)
  • 这个答案帮助我解决了我一直在研究的问题.我的问题来自于对措施如何运作缺乏了解.我的子视图使用match_parent作为其宽度,但我的测量调用使用MeasureSpec.makeMeasureSpec(0,MeasureSpec.UNSPECIFIED)作为width参数.将width参数更改为MeasureSpec.makeMeasureSpec(getWidth(),MeasureSpec.EXACTLY),允许我通过调用view.getMeasuredHeight()从视图中获取正确的高度.谢谢! (2认同)