Android list view inside a scroll view

后端 未结 30 2095
一向
一向 2020-11-21 13:43

I have an android layout which has a scrollView with a number of elements with in it. At the bottom of the scrollView I have a listView

30条回答
  •  一生所求
    2020-11-21 14:08

    Just call this function after assign adapter to listview

    public static void setListViewHeightBasedOnChildren
                (ListView listView) {
            ListAdapter listAdapter = listView.getAdapter();
            if (listAdapter == null) return;
    
            int desiredWidth = View.MeasureSpec.makeMeasureSpec(listView.getWidth(),
                    View.MeasureSpec.UNSPECIFIED);
            int totalHeight = 0;
            View view = null;
            for (int i = 0; i < listAdapter.getCount(); i++) {
                view = listAdapter.getView(i, view, listView);
                if (i == 0) view.setLayoutParams(new
                        ViewGroup.LayoutParams(desiredWidth,
                        ViewGroup.LayoutParams.WRAP_CONTENT));
    
                view.measure(desiredWidth, View.MeasureSpec.UNSPECIFIED);
                totalHeight += view.getMeasuredHeight();
            }
    
            ViewGroup.LayoutParams params = listView.getLayoutParams();
    
            params.height = totalHeight + (listView.getDividerHeight() *
                    (listAdapter.getCount() - 1));
    
            listView.setLayoutParams(params);
            listView.requestLayout();
        } 
    

提交回复
热议问题