ViewGroup中{TextView的,...}。getMeasuredHeight给出错误的值比实际高度小 [英] ViewGroup{TextView,...}.getMeasuredHeight gives wrong value is smaller than real height

查看:294
本文介绍了ViewGroup中{TextView的,...}。getMeasuredHeight给出错误的值比实际高度小的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  { 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返回错误的值...这是不是真正的高度。

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

如何摆脱这个问题?

下面是java code:

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

和这里是list_item_comments.xml:

and here is the list_item_comments.xml:

                         

推荐答案

现在的问题是比较旧的,但我有类似的问题,所以我将描述什么是错的。 其实,在listItem.measure()参数用于错了,你应该设置是这样的:

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

不过,要小心未指定宽度测量规范,它会忽略所有的布局PARAMS,甚至屏幕尺寸,因此要获得正确的高度,首先获得最大宽度查看可以使用和调用措施()是这样的:

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

这篇关于ViewGroup中{TextView的,...}。getMeasuredHeight给出错误的值比实际高度小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆