Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change ListView height dynamically in Android?

I need to change the height of a ListView dynamically in my app.

Is there any way to do that?

like image 988
surendra Avatar asked May 20 '11 11:05

surendra


1 Answers

This piece of code helped me to achieve dynamic listview height.

import android.view.View;
import android.view.ViewGroup;
import android.view.View.MeasureSpec;
import android.widget.ListAdapter;
import android.widget.ListView;

public class Utility {
    public static void setListViewHeightBasedOnChildren(ListView listView) {
        ListAdapter listAdapter = listView.getAdapter();
        if (listAdapter == null) {
            // pre-condition
            return;
        }

        int totalHeight = 0;
        int desiredWidth = MeasureSpec.makeMeasureSpec(listView.getWidth(), MeasureSpec.AT_MOST);
        for (int i = 0; i < listAdapter.getCount(); i++) {
            View listItem = listAdapter.getView(i, null, listView);
            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();
    }
}

In the main Activity use this Utility class to change the listview height.

 phraseListView=(ListView)findViewById(R.id.phrase_listview);
 phraseAdapter=new PhraseListAdapter(this);
 phraseListView.setAdapter(phraseAdapter);
 Utility.setListViewHeightBasedOnChildren(phraseListView);

Taken from here

like image 107
Rafael Avatar answered Oct 06 '22 10:10

Rafael