GridLayoutManager设置分割线时item宽度不相等?

问题:使用GridLayoutManager添加RecyclerView.ItemDecoration出现item不相等的问题。

解决:通过等比计算间距宽度。

核心算法:

            int eachWidth = (spanCount - 1) * spaceMiddle / spanCount; 计算等比间距
            int top = spaceTop;
            int left = position % spanCount * (spaceMiddle - eachWidth);
            if (left >= eachWidth) { // 左边距离出现大于等比间距,就使用等比间距
                left = eachWidth;
            }
            int right = eachWidth - left;
            int bottom = 0;
            outRect.set(left, top, right, bottom);

public class ItemDecorationRight extends RecyclerView.ItemDecoration {
    private int spaceMiddle;
    private int spaceTop;
    private int spanCount;

    public ItemDecorationRight(Context context, int spanCount) {
        this.spanCount = spanCount;
        this.spaceTop = DisplayHelps.dip2px(context, 15);
        this.spaceMiddle = DisplayHelps.dip2px(context, 35);
    }

    @Override
    public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
        int position = parent.getChildLayoutPosition(view);
        if (position <= 8) {
            int eachWidth = (spanCount - 1) * spaceMiddle / spanCount;
            int top = spaceTop;
            int left = position % spanCount * (spaceMiddle - eachWidth);
            if (left >= eachWidth) {
                left = eachWidth;
            }
            int right = eachWidth - left;
            int bottom = 0;
            outRect.set(left, top, right, bottom);
        }
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值