ListView contents get cutoff after Adapter update

前端 未结 3 1680
半阙折子戏
半阙折子戏 2021-01-25 01:02

I have a number of vertically stacked panels in my UI. Each panel contains a ListView. Based on user interaction, the number of items in the ListView gets updated.

My pr

3条回答
  •  南方客
    南方客 (楼主)
    2021-01-25 01:45

    try this function. I think, it might help you. The function is used to set ListView's height based on its children.

    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();
        }
    

提交回复
热议问题