【问题标题】:ViewGroup{TextView,...}.getMeasuredHeight gives wrong value is smaller than real heightViewGroup{TextView,...}.getMeasuredHeight 给出的错误值小于实际高度
【发布时间】:2011-01-12 12:45:42
【问题描述】:
  { 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(ViewGroup 包含的 TextViews 具有长文本,但换行符除外)。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);
}

这里是 list_item_cmets.xml:

【问题讨论】:

    标签: android


    【解决方案1】:

    这个问题很老了,但我有类似的问题,所以我会描述什么是错的。 其实listItem.measure()中的参数用错了,应该这样设置:

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

    但是,请注意未指定的宽度测量规范,它会忽略所有布局参数甚至屏幕尺寸,因此要获得正确的高度,首先要获取视图可以使用的最大宽度并以这种方式调用 measure():

    listItem.measure(MeasureSpec.makeMeasureSpec(maxWidth, MeasureSpec.AT_MOST), MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));
    

    【讨论】:

    • 这对我很有帮助。非常感谢!
    • @user711058 我有同样的问题,但这个解决方案对我不起作用
    • 这个答案帮助我解决了一个我一直在研究的问题。我的问题来自于对测量的工作原理缺乏了解。我的子视图使用 match_parent 作为其宽度,但我的测量调用使用 MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED) 作为宽度参数。将宽度参数更改为 MeasureSpec.makeMeasureSpec(getWidth(), MeasureSpec.EXACTLY),允许我通过调用 view.getMeasuredHeight() 从视图中获取正确的高度。谢谢!
    • 谢谢,这帮助我了解了measure 方法的工作原理,并且可以解决我的问题
    • 谢谢你拯救了我的一天
    【解决方案2】:

    【讨论】:

      【解决方案3】:

      当您的列表视图项的 xml 文件有填充时,它也会给出错误的值。去掉padding,试试margin,效果会很好。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-09-03
        • 1970-01-01
        • 2020-06-01
        • 2023-02-13
        • 1970-01-01
        相关资源
        最近更新 更多