Saturday, March 3, 2012

Android : ListView inside a ScrollView

If there is a requirement  to place listview inside a scrollview , we cant implement it directly because of their vertical scroll property . To achieve this , after calling adpater.notifyDataSetChanged() , find the width and height of the listview  and invoke  requestLayout function. By doing this the performance of the list view become poor because we are changing listview as a normal linearlayout. It becomes a normal view group and child.




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();
 }

No comments:

Post a Comment