recycleview添加边距

本文详细介绍了如何在Android的RecyclerView中为项视图添加内外边距,包括使用ItemDecoration、自定义布局管理器以及在适配器中设置空间等方法。
摘要由CSDN通过智能技术生成

public class RecyclerViewDecoration extends RecyclerView.ItemDecoration {

    private int horizontalSpace; // 整个RecyclerView与左右两侧的间距
    private int verticalSpace; // 整个RecyclerView与上下的间距
    private int leftMargin; // 每个item与左边的间距
    private int topMargin; // 每个item与顶部的间距
    private int rightMargin; // 每个item与右边的间距
    private int bottomMargin; // 每个item与底部的间距

    public RecyclerViewDecoration(int horizontalSpace, int verticalSpace) {
        this(horizontalSpace, verticalSpace, 0, 0, 0, 0);
    }

    public RecyclerViewDecoration(int horizontalSpace, int verticalSpace, int margin) {
        this(horizontalSpace, verticalSpace, margin, margin, margin, margin);
    }

    public RecyclerViewDecoration(int horizontalSpace, int verticalSpace, int leftMargin, int topMargin, int rightMargin, int bottomMargin) {
        this.horizontalSpace = horizontalSpace;
        this.verticalSpace = verticalSpace;
        this.leftMargin = leftMargin;
        this.topMargin = topMargin;
        this.rightMargin = rightMargin;
        this.bottomMargin = bottomMargin;
    }

    @Override
    public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
        super.getItemOffsets(outRect, view, parent, state);
        // 得到当前Item在RecyclerView中的位置,从0开始
        int position = parent.getChildAdapterPosition(view);
        // 得到RecyclerView中Item的总个数
        int co
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值