如何强制listView的高度为大小,以便每一行都可见?

时间:2012-02-28 14:45:51

标签: android android-widget

我有嵌套的listView。如何强制listView的高度为大小,以便每一行都可见? ListView嵌套在ScrollView中,因此滚动不适用于ListView,因此我需要使所有项目在ListView中可见,这是嵌套离子ScrollView(上面有更多内容)。

2 个答案:

答案 0 :(得分:4)

计算listView的高度

public static void setListViewHeightBasedOnChildren(ListView listView) {
    ListAdapter listAdapter = listView.getAdapter();
    if (listAdapter == null) {
        // pre-condition
        return;
    }

    int totalHeight = 0;
    int desiredWidth = MeasureSpec.makeMeasureSpec(listView.getWidth(),
            MeasureSpec.AT_MOST);
    for (int i = 0; i < listAdapter.getCount(); i++) {
        View listItem = listAdapter.getView(i, null, listView);
        listItem.measure(desiredWidth, MeasureSpec.UNSPECIFIED);
        totalHeight += listItem.getMeasuredHeight();
    }

    ViewGroup.LayoutParams params = listView.getLayoutParams();
    params.height = totalHeight
            + (listView.getDividerHeight() * (listAdapter.getCount() - 1));
    listView.setLayoutParams(params);
    listView.requestLayout();
}

将listview对象传递给此方法。

 setListViewHeightBasedOnChildren(listView)

答案 1 :(得分:0)

您可以使用此code.listview包含此属性

android:minheight="20dp";