在使用Android的ScrollView里面嵌套GridView时,设置android:layout_height="wrap_content"属性,运行界面的效果不会出现全部数据,即GridView会显示不全。
解决方法:重写GridView的onMeasure()方法,使其不会出现滚动条即可。
package com.example.gridview; import android.content.Context;
import android.util.AttributeSet;
import android.widget.GridView; public class MyGridView extends GridView { public MyGridView(Context context) {
super(context);
} public MyGridView(Context context, AttributeSet attrs) {
super(context, attrs);
} public MyGridView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
} @Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int expandSpec = MeasureSpec.makeMeasureSpec(
Integer.MAX_VALUE >> 2, MeasureSpec.AT_MOST);
super.onMeasure(widthMeasureSpec, expandSpec);
} }
然后在布局文件里面引用重写的GridView控件。
<com.example.gridview.MyGridView
android:id="@+id/gv1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="@color/gv1"
android:columnWidth="@dimen/itemSize"
android:gravity="center"
android:horizontalSpacing="@dimen/horiz_spac"
android:numColumns="auto_fit"
android:scrollbarStyle="insideOverlay"
android:scrollbars="vertical"
android:stretchMode="columnWidth"
android:verticalSpacing="@dimen/vertc_space" />
最后设置Adapter即可。
package com.example.gridview; import android.app.Activity;
import android.os.Bundle;
import android.widget.GridView; public class MainActivity extends Activity { @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.grid_view); GridView gv=(GridView)findViewById(R.id.gv1);
gv.setAdapter(new GridAdapter(this,R.layout.grid_item));
}
}