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

标签 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(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_comments.xml:

最佳答案

这个问题比较老了,但我遇到了类似的问题,所以我会描述哪里出了问题。 其实listItem.measure()中的参数用错了,应该这样设置:

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

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

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

关于android - ViewGroup{TextView,...}.getMeasuredHeight 给出的错误值小于实际高度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4668939/

相关文章:

android - Android 上的延迟事件

java - 仅对按钮的颜色进行动画处理

android - ArrayAdapter 正在为 ListView 中的每个项目重复 UI Header

android - 想要在单击选项卡时退出应用程序

android - 有没有办法从应用程序内兑换促销代码?

android - 您不能将自定义标题与其他标题功能结合使用

Android:给EditText字段添加小数点,并使其随输入移动

android - 检查手机时钟是否正确

android - 如何在 Android 中设置壁纸?

android - 无法创建 flutter 项目 : No option specified for the output directory error