0

hello everyone i need help to set the the dynamic height to the list view .

In my task there a listView inside scroll view so i need to set the dynamic height to the list view to make the task complete workable in the scroll view.

Im using the below code from how to change the height of the ListView dynamically in andrtoid. This code is working good but problem is with this code it make the duble height to list view .

suppose if there only 3 items in list view then it make the listview height equals to 6 items.

i want know how to resolve it.

Here is my code.

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

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

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

And im using it in listview activity Like:

SimpleAdapter simpleadapter = new SimpleAdapter(getApplicationContext(), alist, R.layout.fragmentsrow, getItems, setItems);

        ListViewWelcomePage.setAdapter(simpleadapter);

        Utility.setListViewHeightBasedOnChildren(ListViewWelcomePage);
Community
  • 1
  • 1
sunny
  • 179
  • 2
  • 14
  • First of all if you are using listview then remove Scrollview. By default if more data is there in list then it will scroll. – Tara Aug 17 '16 at 05:28
  • i need scroll view bro i can't remove scroll view just because there another items below the list view that i need to display using the scroll view – sunny Aug 17 '16 at 05:31
  • Use footer or header in list view instead of nesting list view in scroll view. Something like [this](http://stackoverflow.com/questions/4265228/how-to-add-a-footer-in-listview) – MrOnyszko Aug 17 '16 at 05:39

1 Answers1

0

You can user ExpandableHeightListView instead of normal ListView. Please see this github library https://github.com/PaoloRotolo/ExpandableHeightListView

Titto Jose
  • 72
  • 1
  • 3