ScrollView中嵌套GridView,ListView滚动冲突解决方法

来源:互联网 发布:有限元优化软件 比较 编辑:程序博客网 时间:2024/05/26 19:15

引言

在实际项目中长春会遇见ScrollView与GridView、ListView滚动冲突的问题,因此本文就来记录一下解决该冲突的办法。

问题描述

在ScrollView中嵌套一个带滚动的View,比如GridView会导致GridView显示不全,效果如下图:
这里写图片描述

解决办法

可以自定义GridView来解决这一冲突,很简单,只需要几行代码即可。

package com.winton.component;import android.content.Context;import android.util.AttributeSet;import android.widget.GridView;public class GridviewOnScrollview extends GridView{    public GridviewOnScrollview(Context context) {        super(context);        // TODO Auto-generated constructor stub    }    public GridviewOnScrollview(Context context,AttributeSet attrs) {        // TODO Auto-generated constructor stub        super(context,attrs);    }    public GridviewOnScrollview(Context context,AttributeSet attrs,int defStyle) {        // TODO Auto-generated constructor stub        super(context, attrs, defStyle);    }    @Override    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {        // TODO Auto-generated method stub        int expandSpec = MeasureSpec.makeMeasureSpec(                 Integer.MAX_VALUE >> 2, MeasureSpec.AT_MOST);        super.onMeasure(widthMeasureSpec, expandSpec);    }}

如上所示,只需要重写OnMeasure()方法即可。

//关键代码        int expandSpec = MeasureSpec.makeMeasureSpec(Integer.MAX_VALUE >> 2, MeasureSpec.AT_MOST);        super.onMeasure(widthMeasureSpec, expandSpec);

使用

更改完代码,将其作为自定义控件一样使用,代码如下:

<?xml version="1.0" encoding="utf-8"?><com.winton.component.GridviewOnScrollview xmlns:android="http://schemas.android.com/apk/res/android"    android:id="@+id/gv"    android:layout_width="match_parent"    android:layout_height="match_parent"    android:gravity="center"    android:horizontalSpacing="@dimen/margin_between_channel"    android:numColumns="4"    android:stretchMode="columnWidth"    android:verticalSpacing="@dimen/margin_between_channel"    android:padding="4dip" />

效果

效果还是可以的,基本达到了需求。
这里写图片描述

结尾

今天先到这里,欢迎小伙伴们QQ骚扰。

1 0
原创粉丝点击