最近在做一個項目,有一個需求是在ScrollView中內嵌一個GridView。
剛開始,我是以為能直接內嵌在里面:
1 <ScrollView 2 android:layout_width="match_parent" 3 android:layout_height="0dp" 4 android:layout_weight="5.5"> 5 <GridView 6 android:id="@+id/gridView" 7 android:layout_width="fill_parent" 8 android:layout_height="fill_parent" 9 android:numColumns="auto_fit" 10 android:columnWidth="90dp" 11 android:gravity="center" 12 android:listSelector="@drawable/base_item_selector" 13 android:stretchMode="columnWidth" 14 ></GridView> 15 </ScrollView> 16 <RelativeLayout
1 mGridView = (GridView)findViewById(R.id.gridView); 2 ArrayAdapter adapter = new ArrayAdapter(this,android.R.layout.simple_list_item_1, 3 letters); 4 mGridView.setAdapter(adapter);
運行效果:
只顯示一行。
分析原因:ScrollView和GridView都帶滾動條,引起沖突,導致GridView只能顯示一行。
這就需要自定義GirdView:
1 public class MyGridView extends GridView { 2 public MyGridView(Context context, AttributeSet attrs) { 3 super(context, attrs); 4 } 5 public MyGridView(Context context) { 6 super(context); 7 } 8 public MyGridView(Context context, AttributeSet attrs, int defStyle) { 9 super(context, attrs, defStyle); 10 } 11 @Override 12 public void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { 13 int expandSpec = MeasureSpec.makeMeasureSpec( 14 Integer.MAX_VALUE >> 2, MeasureSpec.AT_MOST); 15 super.onMeasure(widthMeasureSpec, expandSpec); 16 } 17 }
1 <ScrollView 2 android:layout_width="match_parent" 3 android:layout_height="0dp" 4 android:layout_weight="5.5"> 5 <com.johntsai.view.MyGridView 6 android:id="@+id/gridView" 7 android:layout_width="fill_parent" 8 android:layout_height="fill_parent" 9 android:numColumns="auto_fit" 10 android:columnWidth="90dp" 11 android:gravity="center" 12 android:listSelector="@drawable/base_item_selector" 13 android:stretchMode="columnWidth" 14 ></com.johntsai.view.MyGridView> 15 </ScrollView> 16 <RelativeLayout
運行效果:
完美解決。