Set ListView Height Programmatically

前端 未结 3 849
小鲜肉
小鲜肉 2021-01-12 17:01

I have a TextView and ListView in my activity.ListView intially set to Visibility = gone I need a functionality like if u

相关标签:
3条回答
  • 2021-01-12 17:49

    If you want to add ListView on ScrollView and adjust the height of ListView try this code

    if (adapter != null) {
        int totalHeight = 0;
        for (int i = 0; i < adapter.getCount(); i++) {
             View listItem = adapter.getView(i, null, listView);
             listItem.measure(0, 0);
             totalHeight += listItem.getMeasuredHeight() + (listItem.getMeasuredHeightAndState()/2);
        }
        ViewGroup.LayoutParams params = listView.getLayoutParams();
        params.height = totalHeight + (listView.getDividerHeight() * (adapter.getCount() - 1));
        listView.setLayoutParams(params);
        listView.requestLayout();
    
    0 讨论(0)
  • 2021-01-12 17:50

    This will help you.

     ListAdapter listadp = listview.getAdapter();
           if (listadp != null) {
               int totalHeight = 0;
               for (int i = 0; i < listadp.getCount(); i++) {
                   View listItem = listadp.getView(i, null, listview);
                   listItem.measure(0, 0);
                   totalHeight += listItem.getMeasuredHeight();
               }
               ViewGroup.LayoutParams params = listview.getLayoutParams();
               params.height = totalHeight + (listview.getDividerHeight() * (listadp.getCount() - 1));
               listview.setLayoutParams(params);
               listview.requestLayout();
    
    0 讨论(0)
  • 2021-01-12 18:00

    you can try this function to update the height of listView

    public static void updateListViewHeight(ListView myListView) {
        ListAdapter myListAdapter = myListView.getAdapter();
        if (myListAdapter == null) {
            return;
        }
        // get listview height
        int totalHeight = 0;
        int adapterCount = myListAdapter.getCount();
        for (int size = 0; size < adapterCount; size++) {
            View listItem = myListAdapter.getView(size, null, myListView);
            listItem.measure(0, 0);
            totalHeight += listItem.getMeasuredHeight();
        }
        // Change Height of ListView
        ViewGroup.LayoutParams params = myListView.getLayoutParams();
        params.height = (totalHeight
                + (myListView.getDividerHeight() * (adapterCount));
        myListView.setLayoutParams(params);
    }
    
    0 讨论(0)
提交回复
热议问题