recyclerview 加载item ,给特定的item设置上下左右的间距问题

不知道怎么,自己最近的时间老是不想学习,又开始玩一起来了,又在莫名的幻想一起没有用的东西。今天我把我忘记的东西下下来啊,以后在用的时候不用再去翻别人的博客自己博客有那不很好。

给指定的item设置间距,

首页写一个类

pubulic class RecyclerView  extends ReyclerView.ItemDecoration{

//定义局部变量
private int space;


//创建构造起
public RecyclerView(int space){
初始化变量
this.space=space;
}
重写方法
getitemoffsets

@Override
    public void getItemOffsets(Rect outRect, View view,
                               RecyclerView parent, RecyclerView.State state) {
        outRect.left = space;
        outRect.right = space;
        outRect.bottom = space;

        // Add top margin only for the first item to avoid double space between items
        if (parent.getChildPosition(view) == 0)
            outRect.top = space;
    }


}

上面是写的LinearLayoutManager

 

这里是GridLayoutManager或者StaggeredGridLayoutManager 设置Item间距的办法

 

public class GridSpacingItemDecoration extends RecyclerView.ItemDecoration {

   private int spanCount; //列数
   private int spacing; //间隔
   private boolean includeEdge; //是否包含边缘

    public GridSpacingItemDecoration(int spanCount, int spacing, boolean includeEdge) {
        this.spanCount = spanCount;
        this.spacing = spacing;
        this.includeEdge = includeEdge;
    }

    @Override
    public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
       
       //这里是关键,需要根据你有几列来判断
        int position = parent.getChildAdapterPosition(view); // item position
        int column = position % spanCount; // item column

        if (includeEdge) {
            outRect.left = spacing - column * spacing / spanCount; // spacing - column * ((1f / spanCount) * spacing)
            outRect.right = (column + 1) * spacing / spanCount; // (column + 1) * ((1f / spanCount) * spacing)

            if (position < spanCount) { // top edge
                outRect.top = spacing;
            }
            outRect.bottom = spacing; // item bottom
        } else {
            outRect.left = column * spacing / spanCount; // column * ((1f / spanCount) * spacing)
            outRect.right = spacing - (column + 1) * spacing / spanCount; // spacing - (column + 1) * ((1f /    spanCount) * spacing)
            if (position >= spanCount) {
                outRect.top = spacing; // item top
            }
        }
    }
}

调用

int spanCount = 3; // 3 columns int spacing = 50; // 50px boolean includeEdge = false;

mRecyclerView.addItemDecoration(new GridSpacingItemDecoration(spanCount, spacing, includeEdge));


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值