美文网首页
RecycleView间距设置

RecycleView间距设置

作者: 飞哥不是盖的 | 来源:发表于2019-08-13 20:33 被阅读0次

调用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;

        }

}

}

相关文章

网友评论

      本文标题:RecycleView间距设置

      本文链接:https://www.haomeiwen.com/subject/tyhijctx.html