ScrollView GridView ListView 都有上下滑动的响应函数,所以嵌套在一起的话,里面那一层就监听不到滑动的响应。

如果不处理的话,GridView 和 ListView 在ScrollView中只会显示一部分高度,这样看起来不是很郁闷?


在特殊的情况下,我们需要嵌套起来使用才能符合界面的设计.

SO 在网上找了一些时间后,发现解决办法还是有的,一下是我个人觉得简单,易用,缺点不多的一种方法:

自定义一个类 继承GridView或者ListView,重写其中的 onMeasure 方法、、


onMeasure方法是在这个View构造的时候确定它的长度和宽度的方法。

我们重写的时候,要把滚动条设置为没有滚动条,Gridview就会按照有多少行,就显示多少行

废话少说,上代码

1. public class MyGridView extends GridView {
2.
3. private boolean haveScrollbar = true;
4.
5. public MyGridView(Context context) {
6. super(context);
7. }
8.
9. public MyGridView(Context context, AttributeSet attrs) {
10. super(context, attrs);
11. }
12.
13. public MyGridView(Context context, AttributeSet attrs, int defStyle) {
14. super(context, attrs, defStyle);
15. }
16.
17. /**
18. * 设置是否有ScrollBar,当要在ScollView中显示时,应当设置为false。 默认为 true
19. *
20. * @param haveScrollbars
21. */
22. public void setHaveScrollbar(boolean haveScrollbar) {
23. this.haveScrollbar = haveScrollbar;
24. }
25.
26. @Override
27. protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
28. if (haveScrollbars
29. int expandSpec = MeasureSpec.makeMeasureSpec(Integer.MAX_VALUE >>
30. super.onMeasure(widthMeasureSpec, expandSpec);
31. } else {
32. super.onMeasure(widthMeasureSpec, heightMeasureSpec);
33. }
34. }
35. }


public class MyGridView extends GridView {

private boolean haveScrollbar = true;

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);
}

/**
* 设置是否有ScrollBar,当要在ScollView中显示时,应当设置为false。 默认为 true
*
* @param haveScrollbars
*/
public void setHaveScrollbar(boolean haveScrollbar) {
this.haveScrollbar = haveScrollbar;
}

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
if (haveScrollbars == false) {
int expandSpec = MeasureSpec.makeMeasureSpec(Integer.MAX_VALUE >> 2, MeasureSpec.AT_MOST);
super.onMeasure(widthMeasureSpec, expandSpec);
} else {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
}
}

在xml中这么定义:



1. <com.erp.android.control.NDGridView
2. android:id="@+id/myGrideView"
3. android:layout_width="fill_parent"
4. android:layout_height="wrap_content"
5. android:layout_gravity="center"
6. android:columnWidth="100dp"
7. android:gravity="center"
8. android:numColumns="auto_fit" >
9. </com.erp.android.control.MyGridView>


<com.erp.android.control.NDGridView
android:id="@+id/myGrideView"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:columnWidth="100dp"
android:gravity="center"
android:numColumns="auto_fit" >
</com.erp.android.control.MyGridView>

重写就重写了这一个地方,我认为的缺点就是设置之后不能上下滑动了,不过有ScrollView 可以代替这一功能