Set Height of ListView at run time in android

后端 未结 4 978
不知归路
不知归路 2021-01-03 00:40

How to set Height of ListView.

XML Code (This code is working fine and fixed height as 200 dip)



        
相关标签:
4条回答
  • 2021-01-03 00:45

    First Remove import files for LayoutParams and after that Use below code for LayoutParams.

    LinearLayout.LayoutParams params=new LinearLayout.LayoutParams(200, 300);
    convertView.setLayoutParams(params);
    
    0 讨论(0)
  • 2021-01-03 00:51
    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;
        }
    
    }
    
    0 讨论(0)
  • 2021-01-03 00:59

    try this

    public void setDynamicHeight(ListView listView) {
    ListAdapter listAdapter = listView.getAdapter();
        if (listAdapter == null) {
        return;
        }
    int totalHeight = listView.getPaddingTop() + listView.getPaddingBottom();
    int desiredWidth = MeasureSpec.makeMeasureSpec(listView.getWidth(), MeasureSpec.AT_MOST);
    for (int i = 0; i < listAdapter.getCount(); i++) {
        View listItem = listAdapter.getView(i, null, listView);
    
        if(listItem != null){
            listItem.setLayoutParams(new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT));
            listItem.measure(desiredWidth, MeasureSpec.UNSPECIFIED);
            totalHeight += listItem.getMeasuredHeight();
    
        }
    }
    ViewGroup.LayoutParams params = listView.getLayoutParams();
    params.height = totalHeight + (listView.getDividerHeight() * (listAdapter.getCount() - 1));
    listView.setLayoutParams(params);
    listView.requestLayout();}
    
    0 讨论(0)
  • 2021-01-03 01:00

    Try This code..

     LayoutParams lp = (LayoutParams) mListView.getLayoutParams();
     lp.height = 300;
     mListView.setLayoutParams(lp);
    
    0 讨论(0)
提交回复
热议问题