get ListView Height Based On Children - Android android.widget

Android examples for android.widget:ListView

Description

get ListView Height Based On Children

Demo Code

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

public class Main {

  public static int getListViewHeightBasedOnChildren(ListView listView) {
    ListAdapter listAdapter = listView.getAdapter();
    if (listAdapter == null) {
      // pre-condition
      return 0;//from  ww  w . j a v a 2 s  .  c om
    }
    int totalHeight = 0;
    for (int i = 0; i < listAdapter.getCount(); i++) {
      View listItem = listAdapter.getView(i, null, listView);
      listItem.measure(0, 0);
      int itemHeight = listItem.getMeasuredHeight();
      totalHeight += itemHeight;

    }

    int height = (int) (totalHeight + (listView.getDividerHeight() * (listAdapter.getCount() - 1)) + 0.5);

    return height;
  }

}

Related Tutorials