Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

android set listview height dynamically

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 height by code using layoutParams

RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(LayoutParams.MATCH_PARENT, ListViewData.length());

this solution is good but i can't figure the right height that i should give in the Params, SO is there a way to know the actual size from the size of the array

Edit: i came up with a solution that everytime i expand a group of the list am gonna change the height to fit with new geight

like image 595
alaa7731 Avatar asked Oct 01 '13 13:10

alaa7731


1 Answers

try this, Use Child based on listview. setListViewHeightBasedOnChildren() this will set your listview child based height

 public class Utils {

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

    int totalHeight = 0;
    for (int i = 0; i < listAdapter.getCount(); i++) {
        View listItem = listAdapter.getView(i, null, listView);
        listItem.measure(0, 0);
        totalHeight += listItem.getMeasuredHeight();
    }

    ViewGroup.LayoutParams params = listView.getLayoutParams();
    params.height = totalHeight + (listView.getDividerHeight() * (listAdapter.getCount() - 1));
    listView.setLayoutParams(params);
    listView.requestLayout();
}



}
like image 67
Murali Ganesan Avatar answered Oct 18 '22 11:10

Murali Ganesan