RecyclerView divider width with ItemDecoration

737 views Asked by At

I have a RecyclerView and have added an ItemDecoration to it as follows :-

mRecyclerView.addItemDecoration(new DividerItemDecoration(this, DividerItemDecoration.VERTICAL_LIST));

My ItemDecoration looks like :-

public void onDrawOver(Canvas c, RecyclerView parent, RecyclerView.State state)
    {
        final int top = parent.getPaddingTop();
        final int bottom = parent.getHeight() - parent.getPaddingBottom();
        final int childCount = parent.getChildCount();
        for (int i = 0; i < childCount; i++)
        {
            final View child = parent.getChildAt(i);
            final RecyclerView.LayoutParams params = (RecyclerView.LayoutParams) child.getLayoutParams();
            final int left = child.getRight() + params.rightMargin;
            final int right = left + mDivider.getIntrinsicHeight();
            mDivider.setBounds(left, top, right, bottom);
            mDivider.draw(c);
        }
}

This draws a divider taking full width of the screen. I want to add a little margin from the left and right of about 15dp (red line) so that it looks shorter than the screen width something like below :-

enter image description here

How can I achieve this? Any suggestions are appreciated.

2

There are 2 answers

0
Nicolas Duponchel On

Have a look at getItemOffsets method. Something like following should do it.

override fun getItemOffsets(
    rect: Rect,
    view: View,
    parent: RecyclerView,
    state: RecyclerView.State
) {
    rect.right = parent.right - yourMargin
    rect.left = parent.left + yourMargin
}

This method will set the rect space where you'll draw (onDraw(...)) your decoration.

2
Triaro On

Just put the value of

    final int left = 200;
    final int right= 200;