Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Margin between items in recycler view Android

Hi I am Following this tutorial:

http://www.journaldev.com/10024/android-recyclerview-and-cardview-example-tutorial

Now I am facing a weird issue the margin between each CardView item inside RecyclerView is way too much.

ISSUE

How to reduce the Margin between each item of CardView placed inside RecyclerView?

enter image description here

like image 956
Tushar Narang Avatar asked May 29 '16 08:05

Tushar Narang


People also ask

How do I reduce the space between items in RecyclerView?

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

How do I add a divider to my recycler view?

We have to create a default Divider using addItemDecoration() method with the RecyclerView instance, we need to pass the ItemDecoration(in this case it is DividerItemDecoration()) instance and the orientation of the LayoutManager(in this case it is vertical) of the recycler view.


2 Answers

I faced similar issue, with RelativeLayout as the root element for each row in the recyclerview.

To solve the issue, find the xml file that holds each row and make sure that the root element's height is wrap_content NOT match_parent.

like image 99
Maher Nabil Avatar answered Sep 29 '22 22:09

Maher Nabil


I made a class to manage this issue. This class set different margins for the items inside the recyclerView: only the first row will have a top margin and only the first column will have left margin.

public class RecyclerViewMargin extends RecyclerView.ItemDecoration { private final int columns; private int margin;  /**  * constructor  * @param margin desirable margin size in px between the views in the recyclerView  * @param columns number of columns of the RecyclerView  */ public RecyclerViewMargin(@IntRange(from=0)int margin ,@IntRange(from=0) int columns ) {     this.margin = margin;     this.columns=columns;  }  /**  * Set different margins for the items inside the recyclerView: no top margin for the first row  * and no left margin for the first column.  */ @Override public void getItemOffsets(Rect outRect, View view,                            RecyclerView parent, RecyclerView.State state) {      int position = parent.getChildLayoutPosition(view);     //set right margin to all     outRect.right = margin;     //set bottom margin to all     outRect.bottom = margin;     //we only add top margin to the first row     if (position <columns) {         outRect.top = margin;     }     //add left margin only to the first column     if(position%columns==0){         outRect.left = margin;         }     } } 

you can set it in your recyclerview this way

 RecyclerViewMargin decoration = new RecyclerViewMargin(itemMargin, numColumns);  recyclerView.addItemDecoration(decoration); 
like image 44
Victor Avatar answered Sep 29 '22 20:09

Victor