Change Height of a Listview dynamicallyAndroid

前端 未结 8 1672
借酒劲吻你
借酒劲吻你 2021-01-06 23:29

The format of my XML file is as following:

 LinearLayout 

     ScrollView

         RelativeLayout

             LinearLayout

             

        
相关标签:
8条回答
  • 2021-01-07 00:08

    You can use below method to set the height of listview programmatically:

    <ListView
            android:id="@+id/lvMenu"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:background="#ffffff"
            />
    

    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);
    
    0 讨论(0)
  • 2021-01-07 00:12

    If you want to change the height of list view dynamically, you could use,

    list.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT, theSizeIWant));
    
    0 讨论(0)
提交回复
热议问题