Random Guy Random Guy - 2 years ago 131
Android Question

Add margins to divider in RecyclerView

i am building an android app which is using

. I want to add dividers to
, which I did using this code:

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

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

Answer Source

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);

 * Custom divider will be used
public DividerItemDecoration(Context context, int resId) {
    divider = ContextCompat.getDrawable(context, resId);

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);


Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download