Android - 获取ListView项目高度?

Mak*_*tar 18 layout user-interface android listview listviewitem

当列表中没有实际项目时,有没有办法在代码中获取ListViewItem高度?

我的ListViewItem布局:

<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="?android:attr/listPreferredItemHeight">
...
</LinearLayout>  
Run Code Online (Sandbox Code Playgroud)

我试图使用Inflater来获取它:

View convertView = LayoutInflater.from( this )
    .inflate( R.layout.mail_list_row, null );
int itemHeight = convertView.getHeight();
Run Code Online (Sandbox Code Playgroud)

但它返回0;

谢谢!

Dwi*_* Ji 42

试试这个,它会对你有用.

private static final int UNBOUNDED = MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED);

// To calculate the total height of all items in ListView call with items = adapter.getCount()
public static int getItemHeightofListView(ListView listView, int items) {
    ListAdapter adapter = listView.getAdapter();

    int grossElementHeight = 0;
    for (int i = 0; i < items; i++) {
        View childView = adapter.getView(i, null, listView);
        childView.measure(UNBOUNDED, UNBOUNDED);
        grossElementHeight += childView.getMeasuredHeight();
    }
    return grossElementHeight;
}
Run Code Online (Sandbox Code Playgroud)


ash*_*rov 11

优化版本Dwivedi Ji的代码,分隔符高度,没有不必要的参数:

private int calculateHeight(ListView list) {

    int height = 0;

    for (int i = 0; i < list.getCount(); i++) {
        View childView = list.getAdapter().getView(i, null, list);
        childView.measure(MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED), MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));
        height+= childView.getMeasuredHeight();
    }

    //dividers height
    height += list.getDividerHeight() * list.getCount();

    return height;
}
Run Code Online (Sandbox Code Playgroud)

  • 我认为分频器计数应该是`list.getCount() - 1` (3认同)

Ami*_*war 5

在android系统中,只有在渲染完成后,视图才会分配为Width和Height。因此,除非您不会获得listItemHeight,否则除非至少渲染列表。解决问题的方法可能是,设置列表项的最小高度,以便您至少可以使用一些东西,而不是硬编码高度和宽度。