SoFunction
Updated on 2025-03-08

The solution to the GridView nested in ScrollView in Android is only one line

Method 1: It is to calculate the subcolumn heights and display the above-mentioned subcolumns in ListView or GridView:

public 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)); 
((MarginLayoutParams)params).setMargins(15, 15, 15, 15); 
(params);
}

Method 2: Rewrite the onMeasure methods of GridView and ListView and directly give it a large enough height:

Rewrite ListView:

public class MyListView extends ListView { 
public MyListView(Context context) { 
// TODO Auto-generated method stub 
super(context); 
} 
public MyListView(Context context, AttributeSet attrs) { 
// TODO Auto-generated method stub 
super(context, attrs); 
} 
public MyListView(Context context, AttributeSet attrs, int defStyle) { 
// TODO Auto-generated method stub 
super(context, attrs, defStyle); 
} 
@Override 
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { 
// TODO Auto-generated method stub 
int expandSpec = (Integer.MAX_VALUE >> 2, 
MeasureSpec.AT_MOST); 
(widthMeasureSpec, expandSpec); 
} 
}

Rewrite GridView:

public class MyGridView extends GridView{ 
public MyGridView(Context context, AttributeSet attrs) { 
super(context, attrs); 
} 
public MyGridView(Context context) { 
super(context); 
} 
public MyGridView(Context context, AttributeSet attrs, int defStyle) { 
super(context, attrs, defStyle); 
} 
@Override 
public void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { 
int expandSpec = (Integer.MAX_VALUE >> 2, 
MeasureSpec.AT_MOST); 
(widthMeasureSpec, expandSpec); 
} 
}

Layout in xml:

< 
android: 
android:layout_width="fill_parent" 
android:layout_height="wrap_content" 
android:gravity="center" 
android:horizontalSpacing="5dp" 
android:numColumns="4" 
android:stretchMode="columnWidth" 
android:verticalSpacing="6dp" />

The above is the solution to the GridView nested in ScrollView in Android introduced by the editor to you. I hope it will be helpful to you. If you have any questions, please leave me a message and the editor will reply to you in time. Thank you very much for your support for my website!