我想在同一个界面中,使用两个GridView,两个GridView一起上下滚动;
如果直接将两个GridView添加到同一个界面上,它们是各自滚动的。
因此,我考虑使用SrollView,将它们包装一下!
但这样做会提示如下信息:
The vertically scrolling ScrollView should not contain another vertically scrolling widget (GridView)
并且GridView的界面也显示不全,只显示了一部分。
网上搜了一下,使用下面这个方法,效果挺好的!能满足我的需求!
从GridView派生出一个自定义的类(MyGridView),重载其测量方法(onMeasure):
- /**
- * @Type: MyGridView
- * 让GridView可以做ScrollView的子控件,但尺寸不会减小
- */
- 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
- public void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
- int expandSpec = MeasureSpec.makeMeasureSpec(Integer.MAX_VALUE >> 2,
- MeasureSpec.AT_MOST);
- super.onMeasure(widthMeasureSpec, expandSpec);
- }
- }
在XML中,将原来使用系统的GridView,替换成自定义的MyGridView即可:
- <ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
- xmlns:tools="http://schemas.android.com/tools"
- android:layout_width="fill_parent"
- android:layout_height="wrap_content">
- <RelativeLayout
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- tools:context=".MainActivity" >
- <com.gaojinshan.MyGridView
- android:id="@+id/gv_app1"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:horizontalSpacing="0dp"
- android:gravity="center"
- android:numColumns="4"
- android:stretchMode="columnWidth"
- android:verticalSpacing="0dip"
- />
- <com.gaojinshan.MyGridView
- android:id="@+id/gv_app2"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:layout_below="@id/gv_app1"
- android:horizontalSpacing="0dp"
- android:gravity="center"
- android:numColumns="2"
- android:stretchMode="columnWidth"
- android:verticalSpacing="0dip"
- android:scrollbars="none"
- />
- </RelativeLayout>
- </ScrollView>
在SrollView中,嵌套ListView,也可以同样处理,不再赘述!
版权声明:本文为博主原创文章,未经博主允许不得转载。