How to add dividers and spaces between items in RecyclerView?

前端 未结 30 2823
清歌不尽
清歌不尽 2020-11-22 03:27

This is an example of how it could have been done previously in the ListView class, using the divider and dividerHeight parame

30条回答
  •  不思量自难忘°
    2020-11-22 04:16

    public class CommonItemSpaceDecoration extends RecyclerView.ItemDecoration {
    
            private int mSpace = 0;
            private boolean mVerticalOrientation = true;
    
        public CommonItemSpaceDecoration(int space) {
            this.mSpace = space;
        }
    
        public CommonItemSpaceDecoration(int space, boolean verticalOrientation) {
            this.mSpace = space;
            this.mVerticalOrientation = verticalOrientation;
        }
    
        @Override
        public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
            outRect.top = SizeUtils.dp2px(view.getContext(), mSpace);
            if (mVerticalOrientation) {
                if (parent.getChildAdapterPosition(view) == 0) {
                    outRect.set(0, SizeUtils.dp2px(view.getContext(), mSpace), 0, SizeUtils.dp2px(view.getContext(), mSpace));
                } else {
                    outRect.set(0, 0, 0, SizeUtils.dp2px(view.getContext(), mSpace));
                }
            } else {
                if (parent.getChildAdapterPosition(view) == 0) {
                    outRect.set(SizeUtils.dp2px(view.getContext(), mSpace), 0, 0, 0);
                } else {
                    outRect.set(SizeUtils.dp2px(view.getContext(), mSpace), 0, SizeUtils.dp2px(view.getContext(), mSpace), 0);
                }
            }
        }
    }
    

    This will add space in every item's top and bottom(or left and right).Then you can set it to your recyclerView.

    recyclerView.addItemDecoration(new CommonItemSpaceDecoration(16));
    

    SizeUtils.java

    public class SizeUtils {
        public static int dp2px(Context context, float dpValue) {
            final float scale = context.getResources().getDisplayMetrics().density;
            return (int) (dpValue * scale + 0.5f);
        }
    }
    

提交回复
热议问题