How to change ListView height dynamically in Android?

前端 未结 7 884
小鲜肉
小鲜肉 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条回答
  •  Happy的楠姐
    2020-12-03 02:41

    You can use below method to set the height of listview programmatically as per your items:

    
    

    Method used for setting height of listview:

    public static boolean setListViewHeightBasedOnItems(ListView listView) {
    
            ListAdapter listAdapter = listView.getAdapter();
            if (listAdapter != null) {
    
                int numberOfItems = listAdapter.getCount();
    
                // Get total height of all items.
                int totalItemsHeight = 0;
                for (int itemPos = 0; itemPos < numberOfItems; itemPos++) {
                    View item = listAdapter.getView(itemPos, null, listView);
                    float px = 500 * (listView.getResources().getDisplayMetrics().density);
                    item.measure(View.MeasureSpec.makeMeasureSpec((int)px, View.MeasureSpec.AT_MOST), View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));
                    totalItemsHeight += item.getMeasuredHeight();
                }
    
                // Get total height of all item dividers.
                int totalDividersHeight = listView.getDividerHeight() *
                        (numberOfItems - 1);
                // Get padding
                int totalPadding = listView.getPaddingTop() + listView.getPaddingBottom();
    
                // Set list height.
                ViewGroup.LayoutParams params = listView.getLayoutParams();
                params.height = totalItemsHeight + totalDividersHeight + totalPadding;
                listView.setLayoutParams(params);
                listView.requestLayout();
                return true;
    
            } else {
                return false;
            }
    
        }
    

    Then set it like below code:

    MenuAdapter menuAdapter = new MenuAdapter(context, R.layout.menu_item);
                lvMenu.setAdapter(menuAdapter);
                setListViewHeightBasedOnItems(lvMenu);
    

    Hope it will help you.

提交回复
热议问题