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