在SrollView中嵌套GridView或ListView

来源:互联网 发布:java麻将游戏代码算法 编辑:程序博客网 时间:2024/04/30 04:03

我想在同一个界面中,使用两个GridView,两个GridView一起上下滚动;
如果直接将两个GridView添加到同一个界面上,它们是各自滚动的。
因此,我考虑使用SrollView,将它们包装一下!
但这样做会提示如下信息:
The vertically scrolling ScrollView should not contain another vertically scrolling widget (GridView)
并且GridView的界面也显示不全,只显示了一部分。

网上搜了一下,使用下面这个方法,效果挺好的!能满足我的需求!
从GridView派生出一个自定义的类(MyGridView),重载其测量方法(onMeasure):

[java] view plaincopy在CODE上查看代码片派生到我的代码片
  1. /** 
  2.  * @Type: MyGridView 
  3.  * 让GridView可以做ScrollView的子控件,但尺寸不会减小 
  4.  */  
  5. public class MyGridView extends GridView {  
  6.       
  7.     public MyGridView(Context context) {    
  8.         super(context);    
  9.     }    
  10.       
  11.     public MyGridView(Context context, AttributeSet attrs) {    
  12.         super(context, attrs);    
  13.     }    
  14.       
  15.     public MyGridView(Context context, AttributeSet attrs, int defStyle) {    
  16.         super(context, attrs, defStyle);    
  17.     }    
  18.     
  19.     @Override    
  20.     public void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {    
  21.     
  22.         int expandSpec = MeasureSpec.makeMeasureSpec(Integer.MAX_VALUE >> 2,    
  23.                 MeasureSpec.AT_MOST);    
  24.         super.onMeasure(widthMeasureSpec, expandSpec);    
  25.     }      
  26. }    

在XML中,将原来使用系统的GridView,替换成自定义的MyGridView即可:

[html] view plaincopy在CODE上查看代码片派生到我的代码片
  1. <ScrollView xmlns:android="http://schemas.android.com/apk/res/android"  
  2.     xmlns:tools="http://schemas.android.com/tools"  
  3.     android:layout_width="fill_parent"  
  4.     android:layout_height="wrap_content">  
  5. <RelativeLayout   
  6.     android:layout_width="wrap_content"  
  7.     android:layout_height="wrap_content"  
  8.     tools:context=".MainActivity" >  
  9.       
  10.     <com.gaojinshan.MyGridView  
  11.         android:id="@+id/gv_app1"  
  12.         android:layout_width="wrap_content"  
  13.         android:layout_height="wrap_content"  
  14.         android:horizontalSpacing="0dp"  
  15.         android:gravity="center"  
  16.         android:numColumns="4"  
  17.         android:stretchMode="columnWidth"   
  18.         android:verticalSpacing="0dip"  
  19.         />  
  20.   
  21.     <com.gaojinshan.MyGridView  
  22.         android:id="@+id/gv_app2"  
  23.         android:layout_width="wrap_content"  
  24.         android:layout_height="wrap_content"  
  25.         android:layout_below="@id/gv_app1"  
  26.         android:horizontalSpacing="0dp"  
  27.         android:gravity="center"  
  28.         android:numColumns="2"  
  29.         android:stretchMode="columnWidth"   
  30.         android:verticalSpacing="0dip"  
  31.         android:scrollbars="none"  
  32.         />  
  33. </RelativeLayout>  
  34. </ScrollView>  

在SrollView中,嵌套ListView,也可以同样处理,不再赘述!

版权声明:本文为博主原创文章,未经博主允许不得转载。

0 0
原创粉丝点击