Gridview 自定义测量高度

昨晚上 ,写了一个Gridview 显示旅游的图片,但是 不知道为什么 只能显示一行图片,而且我的图片数量超过单行的数量,而且我的高度也写的wrap_content ,按道理来说应该有多少显示多少呀,后来问了一下朋友,GridView 高度应该给一个固定值,跟ListView一样 ,好吧,,,,那高度也不能直接写死啊,那就需要写一个自定义的Gridview 来测量高度了。。。。

废话不多说,上代码。代码里有注释

/**
 * Created by ChenHe on 2016/8/19.
 */
public class MyGridView extends GridView {

    public boolean hasScrollBar = true;

    public MyGridView(Context context) {
        this(context, null);
    }

    public MyGridView(Context context, AttributeSet attrs) {
        super(context, attrs, 0);
    }

    public MyGridView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {

        int expandSpec = heightMeasureSpec;
        if (hasScrollBar) {
            expandSpec = MeasureSpec.makeMeasureSpec(Integer.MAX_VALUE >> 2,
                    MeasureSpec.AT_MOST);
            super.onMeasure(widthMeasureSpec, expandSpec);// 注意这里,这里的意思是直接测量出GridView的高度
        } else {
            super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        }
    }
}

这样就OK了


附上Gridview一些属性



九宫格 android:stretchMode="columnWidth",缩放与列宽大小同步


<GridView

  android:id="@+store/grid"

  android:layout_width="wrap_content"   

  android:layout_height="wrap_content"

  android:layout_below="@store/main_daohang"

  android:numColumns="3"         九宫格一行显示三个

  android:gravity="center"           九宫格居中

  android:verticalSpacing="5dp"     垂直边距5

  android:horizontalSpacing="10dp"     水平边距10

  android:stretchMode="columnWidth"     缩放与列宽大小同步



android:layout_height="wrap_content"
android:layout_height="wrap_content"
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值