How to set the height of ListView is surprisingly complicated.
With wrap_contents, it becomes one, or elements overflow and overflow depending on the device ....
Even if I look it up, I can find a lot of it, but I thought that it wouldn't be easy to do because there were many things that were unexpectedly confusing, such as deep reference, collapse without being aware of the life cycle.
Therefore, it can be easily implemented by using the function described later.
All you have to do is apply the Adapter, prepare this function for the Listview that has the data you want to display set, and pass the Listview as an argument.
If you want to change a part of the height dynamically, I think that it will be cleaner if you add control syntax etc. in the for statement.
Java
ListViewUtil.java
public static void setListViewHeightBasedOnChildren(ListView listView) {
    
    //Get ListAdapter
    ListAdapter listAdapter = listView.getAdapter();
    if (listAdapter == null) {
        //null check
        return;
    }
    //Initialization
    int totalHeight = 0;
    //Measure the height of each item and add
    for (int i = 0; i < listAdapter.getCount(); i++) {
        View listItem = listAdapter.getView(i, null, listView);
        listItem.measure(0, 0);
        totalHeight += listItem.getMeasuredHeight();
    }
    //Get LayoutParams
    ViewGroup.LayoutParams params = listView.getLayoutParams();
    //(Separator height*Number of elements)I'll just add
    params.height = totalHeight + (listView.getDividerHeight() * (listAdapter.getCount() - 1));
    //I'll set height to LayoutParams
    listView.setLayoutParams(params);
}
Kotlin
ListViewUtil.kt
fun setListViewHeightBasedOnChildren(listView:ListView) {
  //Get ListAdapter
  val listAdapter = listView.getAdapter()
  if (listAdapter == null)
  {
    //null check
    return
  }
  //Initialization
  val totalHeight = 0
  //Measure the height of each item and add
  for (i in 0 until listAdapter.getCount())
  {
    val listItem = listAdapter.getView(i, null, listView)
    listItem.measure(0, 0)
    totalHeight += listItem.getMeasuredHeight()
  }
  //Get LayoutParams
  val params = listView.getLayoutParams()
  //(Separator height*Number of elements)I'll just add
  params.height = totalHeight + (listView.getDividerHeight() * (listAdapter.getCount() - 1))
  //I'll set height to LayoutParams
  listView.setLayoutParams(params)
}
If there is a better implementation method, please teach me.
Reference article: Android Listview Measure Height
Recommended Posts