Android Studio Gridview 有时候在xml里padding或者margin后,最后一行显示不全,控件使用自定义Adapter.

Gridview 有时候item在xml里padding或者margin后,最后一行显示不全.这时候需要自定义GridView

package utils;

import android.content.Context;
import android.util.AttributeSet;
import android.widget.GridView;

/**
 * 
 * Created by hyk on 2018/5/2.
 * 
 */

public class MyGridview extends GridView {
    private final int ROW_NUMBER = 3;

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

    public MyGridview(Context context) {
        super(context);
    }

    public MyGridview(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    /**
     * 计算控件的大小
     */
    @Override
    public void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        int measureWidth = measureWidth(widthMeasureSpec);
        int measureHeight = measureHeight(heightMeasureSpec);

        // 计算自定义的ViewGroup中所有子控件的大小
        measureChildren(widthMeasureSpec, heightMeasureSpec);

        // 设置自定义的控件MyViewGroup的大小
        setMeasuredDimension(measureWidth, measureHeight);

    }

    private int measureWidth(int pWidthMeasureSpec) {
        int result = 0;
        int widthMode = MeasureSpec.getMode(pWidthMeasureSpec);// 得到模式
        int widthSize = MeasureSpec.getSize(pWidthMeasureSpec);// 得到尺寸

        switch (widthMode) {
            case MeasureSpec.AT_MOST:
            case MeasureSpec.EXACTLY:
                result = widthSize;
                break;
        }
        return result;
    }

    private int measureHeight(int pHeightMeasureSpec) {
        int result = 0;

        int heightMode = MeasureSpec.getMode(pHeightMeasureSpec);
        int heightSize = MeasureSpec.getSize(pHeightMeasureSpec);

        switch (heightMode) {
            case MeasureSpec.AT_MOST:
            case MeasureSpec.EXACTLY:
                result = heightSize;
                break;
        }
        return result;
    }
}
在adapter中的getView 中这样写

@Override
public View getView(int position, View convertView, ViewGroup parent) {

    Holder holder;
    if (convertView == null) {
        ....
        convertView.setTag(holder);
    } else {
        holder = (Holder) convertView.getTag();
    }

    //高度计算
    AbsListView.LayoutParams param = new AbsListView.LayoutParams(
            ViewGroup.LayoutParams.MATCH_PARENT,
            dp2px(context,100));

    convertView.setLayoutParams(param);
    return convertView;
}

这样就基本ok了

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值