Textview getMeasuredHeight不正确多行的高度

时间:2015-05-11 09:31:40

标签: android textview

我使用下面的方法将ListView的高度设置为项目的高度。问题是我有一些文本太长的项目,所以它继续在下一行。对于那些物品,我没有得到适当的高度,但单个项目的高度。我怎样才能使它适用于多行项目?

public boolean setListViewHeightBasedOnItems(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);
            float px = 300 * (listView.getResources().getDisplayMetrics().density);
            item.measure(View.MeasureSpec.makeMeasureSpec((int)px, View.MeasureSpec.AT_MOST), View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));

            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 version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:paddingTop="3dp"
    android:paddingBottom="3dp"
    android:layout_height="wrap_content">

    <TextView
        android:textColor="@color/black"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="New Text"
        android:id="@+id/itemName"
        android:layout_marginRight="5dp"
        android:layout_gravity="right"
        android:layout_centerVertical="true"
        android:layout_toStartOf="@+id/itemData"
        android:layout_alignParentStart="true" />

    <TextView
        android:textColor="@color/black"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="New Text"
        android:id="@+id/itemData"
        android:layout_marginRight="10dp"
        android:layout_alignBaseline="@+id/itemName"
        android:layout_alignParentEnd="true" />

</RelativeLayout>

0 个答案:

没有答案