使用两个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.MyGridViewandroid: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.MyGridViewandroid: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>
在GridView所在页的其他控件的XML里配置上focusableInTouchMode=true,如下所示:
- android:focusable="true"
- android:focusableInTouchMode="true"
在点击切换到该页面时,使用ScrollView的smoothScrollTo(0, 0)方法,将滚动条置顶
public void onClick(View v) {mViewPager.setCurrentItem(item);View view = mViewPager.getChildAt(item);if (view != null) {((ScrollView) view).smoothScrollTo(0, 0);}}