How to configure ListView to automatically change its height?

前端 未结 5 1627
梦毁少年i
梦毁少年i 2021-01-03 04:50

I have three ListView widgets in the same LinearLayout. Something like this (I\'m omitting XML elements that are not relevant in this example):

5条回答
  •  一整个雨季
    2021-01-03 05:36

    i found a solution on set ListView Height Based On Children, this work

    public static void setListViewHeightBasedOnChildren(ListView listView) {
        ListAdapter listAdapter = listView.getAdapter(); 
        if (listAdapter == null) {
            // pre-condition
            return;
        }
    
        int totalHeight = 0;
        for (int i = 0; i < listAdapter.getCount(); i++) {
            View listItem = listAdapter.getView(i, null, listView);
            listItem.measure(0, 0);
            totalHeight += listItem.getMeasuredHeight();
        }
    
        ViewGroup.LayoutParams params = listView.getLayoutParams();
        params.height = totalHeight + (listView.getDividerHeight() * (listAdapter.getCount() - 1));
        listView.setLayoutParams(params);
        listView.requestLayout();
    }
    

提交回复
热议问题