SoFunction
Updated on 2025-03-08

Android Notes: Methods to nest ListView in ScrollView

A few days ago, due to the needs of the project, another ListView should be placed in a ListView, that is, another ListView should be placed in each ListItem of a ListView. But at the beginning, you will find that the small ListView you put in will not display completely, and there is always a problem with its height. After checking the Internet, I found that others also encountered such problems, and most people do not recommend such a design, because by default, Android prohibits the placement of another ScrollView in the ScrollView, and its height cannot be calculated.

After searching again, I found that there is a great man on * that has solved this problem. After experimenting, it can solve the problem. Its idea is to set the Adapter of ListView, recalculate the height of the ListView based on the subitem of ListView, and then set the height to ListView as LayoutParams, so that its height is correct.
The following is the source code:
Copy the codeThe code is as follows:

    public class Utility {
        public static void setListViewHeightBasedOnChildren(ListView listView) {
            ListAdapter listAdapter = ();
            if (listAdapter == null) {
                // pre-condition
                return;
            }
            int totalHeight = 0;
            for (int i = 0; i < (); i++) {
                View listItem = (i, null, listView);
                (0, 0);
                totalHeight += ();
            }
            params = ();
            = totalHeight + (() * (() - 1));
            (params);
        }
    }

Just call this static method after setting the Adapter of the ListView to make the ListView correctly display in the ListItem of its parent ListView. But it should be noted that each Item of the sublistView must be a LinearLayout, not another, because other Layouts (such as RelativeLayout) do not rewrite onMeasure(), so an exception will be thrown when onMeasure() is present.

Another problem with nesting ListView (or ScrollView) in ScrollView is that the child ScrollView cannot slide (if it does not display completely), because the sliding event will be eaten by the parent ScrollView. If you want the child ScrollView to slide, you can only forcefully intercept the sliding event. Some great people posted a code in the forum saying that it is OK. Although I haven't tried it myself, it probably works.

Although the technical difficulties of displaying ScrollView in ScrollView can be solved, such a design is a very poor user experience because users will not easily see and operate the content in the sub-ScrollView. For example, a good design is that each Item of the parent ListView only displays a general description, and then clicking its Item will enter another page to describe and display in detail and operate on this Item.