I use several ListViews to display two lists in one window, I know that the solution is not really, but in my case it turned out to be faster. I assign the height to the ListView, considering the height of all its child elements, the elements are ordinary TextView and it is considered to be generally correct except for the cases when the TextView is split into several lines, then the height is set less than it actually is. Here is the code that calculates the height of the children:

public static void setListViewHeightBasedOnChildren(ListView listView) { ListAdapter listAdapter = listView.getAdapter(); if (listAdapter == null) return; int desiredWidth = View.MeasureSpec.makeMeasureSpec(listView.getWidth(), View.MeasureSpec.UNSPECIFIED); int totalHeight = 0; View view = null; for (int i = 0; i < listAdapter.getCount(); i++) { view = listAdapter.getView(i, view, listView); if (i == 0) view.setLayoutParams(new ViewGroup.LayoutParams(desiredWidth, LinearLayout.LayoutParams.WRAP_CONTENT)); view.measure(desiredWidth, View.MeasureSpec.UNSPECIFIED); totalHeight += view.getMeasuredHeight(); } ViewGroup.LayoutParams params = listView.getLayoutParams(); params.height = totalHeight + (listView.getDividerHeight() * (listAdapter.getCount() - 1)); listView.setLayoutParams(params); } 

How can I correctly calculate the height of all children in the list?

    1 answer 1

    Well, as an option, if it does not take into account the number of lines, then you can try to count how many lines in a TextView - textView.getLinesCount(); and set the tag value for each View .

    Then you call the code line

     view = listAdapter.getView(i, view, listView); 

    get the view.getTag(); value from there view.getTag(); and depending on the number of rows, add the desired value to the total height of the ListView .

    It is rather a crutch than a solution, but suddenly it will help!