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
?
Try to use cardElevation=0dp. This should remove the extra spacing between recyclerview items.
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.
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
.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With