See this Image
I achieved the current margin from xml layout but its not same through all four sides.
How to get equal margin
My current xml layout
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="300dp">
<ImageView
android:id="@+id/iv_photo"
android:layout_width="match_parent"
android:layout_height="300dp"
android:layout_marginEnd="6dp"
android:layout_marginTop="6dp"
android:adjustViewBounds="true"
android:background="@color/colorPrimary"
android:foreground="?android:attr/selectableItemBackground"
android:scaleType="fitXY" />
</RelativeLayout>
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.
You can use ItemDecoration
for this purpose
public class SpacesItemDecoration extends RecyclerView.ItemDecoration {
private int space;
public SpacesItemDecoration(int space) {
this.space = space;
}
@Override
public void getItemOffsets(Rect outRect, View view,
RecyclerView parent, RecyclerView.State state) {
outRect.left = space;
outRect.right = space;
outRect.bottom = space;
// Add top margin only for the first item to avoid double space between items
if (parent.getChildLayoutPosition(view) == 0) {
outRect.top = space;
} else {
outRect.top = 0;
}
}
}
This is how you will use it in java code
mRecyclerView = (RecyclerView) rootView.findViewById(R.id.my_recycler_view);
int spacingInPixels = getResources().getDimensionPixelSize(R.dimen.spacing);
mRecyclerView.addItemDecoration(new SpacesItemDecoration(spacingInPixels));
This solution was provided by @ianhanniballake. Hope this will help you.
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