Recently in a project, there is a need to embed a GridView in ScrollView.
At first, I thought I could embed it directly inside:
1 <ScrollView2 Android:layout_width= "Match_parent"3 Android:layout_height= "0DP"4 Android:layout_weight= "5.5">5 <GridView6 Android:id= "@+id/gridview"7 Android:layout_width= "Fill_parent"8 Android:layout_height= "Fill_parent"9 Android:numcolumns= "Auto_fit"Ten Android:columnwidth= "90DP" One android:gravity= "Center" A Android:listselector= "@drawable/base_item_selector" - Android:stretchmode= "ColumnWidth" - ></GridView> the </ScrollView> - <Relativelayout
1 mgridview = (GridView) Findviewbyid (R.id.gridview); 2 New Arrayadapter (this, Android. R.layout.simple_list_item_1,3 letters); 4 Mgridview.setadapter (adapter);
Operating effect:
Only one row is displayed.
Analysis reason: Both ScrollView and GridView have scrollbars, causing conflicts, causing the GridView to display only one row.
This requires a custom Girdview:
1 Public classMyGridViewextendsGridView {2 PublicMyGridView (Context context, AttributeSet attrs) {3 Super(context, attrs);4 }5 PublicMyGridView (Context context) {6 Super(context);7 }8 PublicMyGridView (context context, AttributeSet attrs,intDefstyle) {9 Super(context, attrs, defstyle);Ten } One @Override A Public voidOnmeasure (intWidthmeasurespec,intHeightmeasurespec) { - intExpandspec =Measurespec.makemeasurespec ( -Integer.max_value >> 2, measurespec.at_most); the Super. Onmeasure (Widthmeasurespec, expandspec); - } -}
1 <ScrollView2 Android:layout_width= "Match_parent"3 Android:layout_height= "0DP"4 Android:layout_weight= "5.5">5 <Com.johntsai.view.MyGridView6 Android:id= "@+id/gridview"7 Android:layout_width= "Fill_parent"8 Android:layout_height= "Fill_parent"9 Android:numcolumns= "Auto_fit"Ten Android:columnwidth= "90DP" One android:gravity= "Center" A Android:listselector= "@drawable/base_item_selector" - Android:stretchmode= "ColumnWidth" - ></Com.johntsai.view.MyGridView> the </ScrollView> - <Relativelayout
Operating effect:
Perfect solution.
Android Learning--How to embed the GridView in ScrollView