如何在recyclerview项目之间设置相等的保证金

Rau*_*rma 5 android android-recyclerview

这个图片

看到这张图片

我从xml布局中获得了当前的余量,但是在所有四个方面都不一样.

如何获得相等的保证金

我目前的xml布局

<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>
Run Code Online (Sandbox Code Playgroud)

Zee*_*bir 11

你可以用它ItemDecoration来达到这个目的

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;
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

这是你在java代码中使用它的方法

mRecyclerView = (RecyclerView) rootView.findViewById(R.id.my_recycler_view);
int spacingInPixels = getResources().getDimensionPixelSize(R.dimen.spacing);
mRecyclerView.addItemDecoration(new SpacesItemDecoration(spacingInPixels));
Run Code Online (Sandbox Code Playgroud)

该解决方案由@ianhanniballake提供.希望这会帮助你.


Bip*_*and 0

使用 DividerItemDecoration 类。
作为参考,请点击此链接如何在 RecyclerView 中的项目之间添加分隔线和空格?