RecycleView间距设置

调用addItemDecoration设置recycleView的间距,不过需要我们自己实现这个类
mRecyclerView.addItemDecoration(new SpaceItemDecoration(0, ArtUtils.dip2px(context,10)));

设置recycleView的间距类,全部代码如下:

public class SpaceItemDecorationextends RecyclerView.ItemDecoration{

private int leftRight;

    private int topBottom;

    //leftRight为横向间的距离 topBottom为纵向间距离

    public SpaceItemDecoration(int leftRight, int topBottom) {

this.leftRight = leftRight;

        this.topBottom = topBottom;

    }

@Override

    public void onDraw(Canvas c, RecyclerView parent, RecyclerView.State state) {

super.onDraw(c, parent, state);

    }

@Override

    public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {

LinearLayoutManager layoutManager = (LinearLayoutManager) parent.getLayoutManager();

        //竖直方向的

        if (layoutManager.getOrientation() == LinearLayoutManager.VERTICAL) {

//最后一项需要 bottom

            if (parent.getChildAdapterPosition(view) == layoutManager.getItemCount() -1) {

outRect.bottom =topBottom;

            }

outRect.top =topBottom;

            outRect.left =leftRight;

            outRect.right =leftRight;

        }else {

//最后一项需要right

            if (parent.getChildAdapterPosition(view) == layoutManager.getItemCount() -1) {

outRect.right =leftRight;

            }

outRect.top =topBottom;

            outRect.left =leftRight;

            outRect.bottom =topBottom;

        }

}

}

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容