Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 920
Random Guy Avatar asked Jan 09 '17 11:01

Random Guy


People also ask

What is DividerItemDecoration?

DividerItemDecoration is a RecyclerView. ItemDecoration that can be used as a divider between items of a LinearLayoutManager . It supports both HORIZONTAL and VERTICAL orientations.

How do I reduce the space between items in RecyclerView?

Try to use cardElevation=0dp. This should remove the extra spacing between recyclerview items.


1 Answers

I think the most straightforward solution is to use the setDrawable method on the Decoration object and pass it an inset drawable with the inset values you want for the margins. Like so:

int[] ATTRS = new int[]{android.R.attr.listDivider};  TypedArray a = context.obtainStyledAttributes(ATTRS); Drawable divider = a.getDrawable(0); int inset = getResources().getDimensionPixelSize(R.dimen.your_margin_value); InsetDrawable insetDivider = new InsetDrawable(divider, inset, 0, inset, 0); a.recycle();  DividerItemDecoration itemDecoration = new DividerItemDecoration(context, DividerItemDecoration.VERTICAL); itemDecoration.setDrawable(insetDivider); recyclerView.addItemDecoration(itemDecoration); 
like image 156
SeptimusX75 Avatar answered Oct 08 '22 21:10

SeptimusX75