android set listview height dynamically

前端 未结 4 1362
情话喂你
情话喂你 2021-01-02 23:39

i have ExpandableListview inside ScrollView and i know that\'s not good but i had too, the only solution to show the whole list is by set its heigh

4条回答
  •  时光取名叫无心
    2021-01-02 23:57

    Try this, it works for my same problem

    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);
            item.measure(0, 0);
            totalItemsHeight += item.getMeasuredHeight();
        }
    
        // Get total height of all item dividers.
        int totalDividersHeight = listView.getDividerHeight() * 
                (numberOfItems - 1);
    
        // Set list height.
        ViewGroup.LayoutParams params = listView.getLayoutParams();
        params.height = totalItemsHeight + totalDividersHeight;
        listView.setLayoutParams(params);
        listView.requestLayout();
    
        return true;
    
    } else {
        return false;
    }}
    

    requestLayout() method is called on the view because something has changed that invalidated its layout - forces redrawing.

提交回复
热议问题