How to change ListView height dynamically in Android?

前端 未结 7 854
小鲜肉
小鲜肉 2020-12-03 02:19

I need to change the height of a ListView dynamically in my app.

Is there any way to do that?

相关标签:
7条回答
  • 2020-12-03 02:51

    You have to create a new control that extends the listview overwhriting some functions

    public class WrapContentListView extends ListView {
        public WrapContentListView(Context context) {
            super(context);
        }
    
        public WrapContentListView(Context context, AttributeSet attrs) {
            super(context, attrs);
        }
    
        public WrapContentListView(Context context, AttributeSet attrs, int defStyle) {
            super(context, attrs, defStyle);
        }
    
        @Override
        public void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
            int expandSpec = MeasureSpec.makeMeasureSpec(Integer.MAX_VALUE >> 2,
                    MeasureSpec.AT_MOST);
            super.onMeasure(widthMeasureSpec, expandSpec);
        }
    
        @Override
        public void setAdapter(ListAdapter adapter) {
            super.setAdapter(adapter);
            setHeightWrapContent();
        }
    
        public void setHeightWrapContent() {
            ListAdapter listAdapter = getAdapter();
            if (listAdapter == null) {
                return;
            }
            int totalHeight = 0;
            for (int i = 0; i < listAdapter.getCount(); i++) {
                View listItem = listAdapter.getView(i, null, this);
                listItem.measure(0, 0);
                totalHeight += listItem.getMeasuredHeight();
            }
    
            ViewGroup.LayoutParams params = this.getLayoutParams();
    
            params.height = totalHeight
                    + (this.getDividerHeight() * (listAdapter.getCount() - 1));
            this.setLayoutParams(params);
        }
    }
    

    https://github.com/mzlogin/WrapContentListView/blob/master/app/src/main/java/org/mazhuang/wrapcontentlistview/WrapContentListView.java

    0 讨论(0)
提交回复
热议问题