1

我在滚动视图中有列表视图,并计算孩子的高度基础。这是我使用的代码:

 public static void SetListViewHeightBasedOnChildren (ListView listView)
    {
        IListAdapter listAdapter = listView.Adapter;
        if (listAdapter == null) {
            // pre-condition
            return;
        }

        int totalHeight = listView.PaddingTop + listView.PaddingBottom;

        for (int i = 0; i < listAdapter.Count; i++) {
            View listItem = listAdapter.GetView (i, null, listView);
            listItem.LayoutParameters = new Android.Views.ViewGroup.LayoutParams (
                ViewGroup.LayoutParams.WrapContent, ViewGroup.LayoutParams.WrapContent);

            listItem.Measure (0, 0);
            totalHeight += listItem.MeasuredHeight;
        }

        ViewGroup.LayoutParams params_ = listView.LayoutParameters;
        params_.Height = totalHeight + (listView.DividerHeight * listAdapter.Count) + 50;
        listView.LayoutParameters = params_;
        listView.RequestLayout ();
    }

一般来说,它工作得很好,但在某些情况下(如果 listview 项目太大等)它修剪的最后一行。

.xml 中的层次结构

滚动视图->RelativeLayout->LinearLayout->ListView

在此处输入图像描述

4

1 回答 1

0
 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();
}
于 2018-11-01T12:39:33.670 回答