SoFunction
Updated on 2025-03-08

Discussion: How to nest ListView in ScrollView

3. Set properties for ScrollView: android:fillViewport="true"
During the test, I found that if the ListView loads not much data, it can be solved, but when the ListView loads a lot of data, it still cannot display completely, and the ListView itself cannot scroll.

3. There are two solutions
1. Calculate the total height of the listview and set it

ListView listView = (ListView) findViewById(id);
YourAdapter adapter = new MyAdapter("Initialize your adapter");
(adapter);
setListViewHeightBasedOnChildren(listView); (Calculate method after setAdapter)

Copy the codeThe code is as follows:

/**
* @param listView
*/
private void setListViewHeightBasedOnChildren(ListView listView) {
 
ListAdapter listAdapter = ();
if (listAdapter == null) {
return;
}
 
int totalHeight = 0;
for (int i = 0; i < (); i++) {
View listItem = (i, null, listView);
(0, 0);
totalHeight += ();
}
 
params = ();
= totalHeight
+ (() * (() - 1));
(params);
}

Note that using this method: 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.
2. Customize ListView, overload the onMeasure() method, and set all displays
Copy the codeThe code is as follows:

package ;
 
import ;
 
/**
*
* @Description: Simple implementation of embedded listview in scrollview
*
* @File:
*
* @Paceage
*
*
* @Date 03:02:38 pm
*
* @Version
*/
public class ScrollViewWithListView extends ListView {
 
public ScrollViewWithListView( context,
attrs) {
super(context, attrs);
}
 
/**
* Integer.MAX_VALUE >> 2. If not set, the system default setting is to display two pieces
*/
public void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int expandSpec = (Integer.MAX_VALUE >> 2,
MeasureSpec.AT_MOST);
(widthMeasureSpec, expandSpec);
 
}
 
}

Helpless and don't know how to solve it, so use it first
Copy the codeThe code is as follows:

(new Runnable() { 
//Let the scrollview jump to the top, it must be placed in the runnable() method
    @Override 
    public void run() { 
     (0, 0); 
     } 
   });

If this method is too much, I hope someone who knows it will give you some solutions.
3. Use scrollView +LinearLayout to add the list using the addView() method.