androidandroid-recyclerviewdivider

Add margins to divider in RecyclerView


i am building an android app which is using RecyclerView. I want to add dividers to RecyclerView, which I did using this code:

DividerItemDecoration dividerItemDecoration = new DividerItemDecoration(recyclerView.getContext(), linearLayoutManager.getOrientation());
recyclerView.addItemDecoration(dividerItemDecoration);

So far everything works fine. However, the divider is taking the size of full screen and I want to add margins to it. Is there any way that I can add margins to the divider using a method that will add some space to the rectangle drawn and not by creating a custom drawable shape with margins and add it to the RecyclerView?


Solution

  • Use this and customize according to your requirement.

    public class DividerItemDecoration extends RecyclerView.ItemDecoration {
    
        private static final int[] ATTRS = new int[]{android.R.attr.listDivider};
    
        private Drawable divider;
    
        /**
         * Default divider will be used
         */
        public DividerItemDecoration(Context context) {
            final TypedArray styledAttributes = context.obtainStyledAttributes(ATTRS);
            divider = styledAttributes.getDrawable(0);
            styledAttributes.recycle();
        }
    
        /**
         * Custom divider will be used
         */
        public DividerItemDecoration(Context context, int resId) {
            divider = ContextCompat.getDrawable(context, resId);
        }
    
        @Override
        public void onDraw(Canvas c, RecyclerView parent, RecyclerView.State state) {
            int left = parent.getPaddingLeft();
            int right = parent.getWidth() - parent.getPaddingRight();
    
            int childCount = parent.getChildCount();
            for (int i = 0; i < childCount; i++) {
                View child = parent.getChildAt(i);
    
                RecyclerView.LayoutParams params = (RecyclerView.LayoutParams) child.getLayoutParams();
    
                int top = child.getBottom() + params.bottomMargin;
                int bottom = top + divider.getIntrinsicHeight();
    
                divider.setBounds(left, top, right, bottom);
                divider.draw(c);
            }
        }
    }