1、创建SpacesItemDecoration辅助类
public class SpacesItemDecoration extends RecyclerView.ItemDecoration {
private int space;
public SpacesItemDecoration(int space) {
this.space = space;
}
@Override
public void getItemOffsets(Rect outRect, @NonNull View view, RecyclerView parent, @NonNull RecyclerView.State state) {
// outRect.left = space;
// outRect.right = space;
// outRect.bottom = space;
outRect.top = space;
// Add top margin only for the first item to avoid double space between items
if (parent.getChildLayoutPosition(view) == 0) {
outRect.top = space;
}
}
public static int px2dp(float dpValue) {
return (int) (0.5f + dpValue * Resources.getSystem().getDisplayMetrics().density);
}
}
2、使用SpacesItemDecoration辅助类
RecyclerView.addItemDecoration(new SpacesItemDecoration(SpacesItemDecoration.px2dp(12)));