Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to set equal margin between recyclerview items

This image

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>
like image 807
Raunak Verma Avatar asked Jul 07 '17 06:07

Raunak Verma


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.


1 Answers

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.

like image 75
Zeeshan Shabbir Avatar answered Nov 12 '22 21:11

Zeeshan Shabbir