尝试计算列表视图的高度时出现问题,该列表视图具有列表项内的多行TextView

时间:2015-05-04 06:20:27

标签: android listview textview

我正在使用这种方法来计算listview的高度,但它并不是我想要的。因为,当内容太长时,我的listview有一个TextView可能是多行的。当TextView在线时它是正确的,但是当它有2条线时,它的高度是错误的。谢谢!

Please see the error in this picture

public static boolean setListViewHeightBasedOnChildren(ListView listView) {
        ListAdapter listAdapter = listView.getAdapter();
        if (listAdapter != null) {
            int numberOfItems = listAdapter.getCount();

            // Get total height of all items.
            int totalItemsHeight = 0;
            for (int itemPos = 0; itemPos < numberOfItems; itemPos++) {
                View item = listAdapter.getView(itemPos, null, listView);
                item.measure(0, 0);
                totalItemsHeight += item.getMeasuredHeight();
            }

            // Get total height of all item dividers.
            int totalDividersHeight = listView.getDividerHeight() *
                    (numberOfItems - 1);

            // Set list height.
            ViewGroup.LayoutParams params = listView.getLayoutParams();
            params.height = totalItemsHeight + totalDividersHeight;
            listView.setLayoutParams(params);
            listView.requestLayout();

            return true;

        } else {
            return false;
        }
    }

XML

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="@color/red"
    android:orientation="vertical">


            <TextView
            android:id="@+id/tv_name"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginRight="@dimen/border_margin"
            android:text="name"
                android:paddingLeft="200dp"
            android:textColor="@color/header_lounge"
            android:textSize="@dimen/text_normal"
            android:textStyle="bold" />

</LinearLayout>

1 个答案:

答案 0 :(得分:4)

ListView变为多行时,所有可用于根据儿童计算TextView高度的方法都会失败。

我也遇到了同样的问题,经过多次尝试后,我找到了解决这个问题的方法。

  

主要概念是,如果您设置了TextView所拥有的确切行数,那么将正确计算高度,即您需要如何执行以下操作,

textView.setLines(numberOfLines)

有了这个,你的问题就会解决。

现在接下来的问题是如何知道TextView将动态生成的确切行数。

我会说这完全取决于你的情景。就我而言,我所做的是,

textView.setText(fullString);

WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
Display display = wm.getDefaultDisplay();
int screenWidth = display.getWidth(); // Get full screen width
int eightyPercent = (screenWidth * 80) / 100; // Calculate 80% of it
// as my adapter was having almost 80% of the whole screen width

float textWidth = textView.getPaint().measureText(fullString);
// this method will give you the total width required to display total String

int numberOfLines = ((int) textWidth/eightyPercent) + 1;
// calculate number of lines it might take

textView.setLines(numberOfLines);