luoj 2011-08-17
前些日子在开发中用到了需要ScrollView嵌套GridView的情况,由于这两款控件都自带滚动条,当他们碰到一起的时候便会出问题,即GridView会显示不全。
解决办法,自定义一个GridView控件
<span style="color:#000000;">public class MyGridView extends GridView { <br /> public MyGridView(Context context, AttributeSet attrs) { <br /> super(context, attrs); <br /> } <br /><br /> public MyGridView(Context context) { <br /> super(context); <br /> } <br /><br /> public MyGridView(Context context, AttributeSet attrs, int defStyle) { <br /> super(context, attrs, defStyle); <br /> } <br /><br /> @Override <br /> public void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { <br /><br /> int expandSpec = MeasureSpec.makeMeasureSpec( <br /> Integer.MAX_VALUE >> 2, MeasureSpec.AT_MOST); <br /> super.onMeasure(widthMeasureSpec, expandSpec); <br /> } <br />}</span>
该自定义控件只是重写了GridView的onMeasure方法,使其不会出现滚动条,ScrollView嵌套ListView也是同样的道理,不再赘述。
XML布局代码
<span style="color:#000000;"><ScrollView Android:layout_height="wrap_content" <br /> android:layout_width="fill_parent" android:id="@+id/scroll_content"> <br /> <com.yourclass.MyGridView xmlns:android="http://schemas.android.com/apk/res/android" <br /> android:id="@+id/grid_view" android:layout_width="fill_parent" <br /> android:layout_height="wrap_content" android:numColumns="auto_fit" <br /> android:horizontalSpacing="1dip" android:verticalSpacing="1dip" <br /> android:columnWidth="150dip" android:stretchMode="columnWidth" <br /> android:gravity="center"> <br /> <br /> </com.yourclass.MyGridView> <br /> </ScrollView></span>
Java调用代码
<span style="color:#000000;">MyGridView gridview = (MyGridView) findViewById(R.id.grid_view); <br />gridview.setAdapter(new ImageAdapter(this));</span>