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

时间:2017-07-07 06:56:18

标签: android android-recyclerview

This image

See this Image

我从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>

3 个答案:

答案 0 :(得分:9)

您可以将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;
    }
  }
}

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

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

此解决方案由@ianhanniballake提供。希望这会对你有所帮助。

答案 1 :(得分:0)

使用DividerItemDecoration类。
参考此链接How to add dividers and spaces between items in RecyclerView?

答案 2 :(得分:0)

在RecyclerView中仅提供左边距和下边距

<android.support.v7.widget.RecyclerView
    android:id="@+id/recyclerView"
    android:layout_marginLeft="10dp"
    android:layout_marginStart="10dp"
    android:layout_marginBottom="10dp"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

</android.support.v7.widget.RecyclerView>

并在item_recyclerview_layout中 对于recyclerView项目给出顶部和右边距

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:layout_marginEnd="10dp"
android:layout_marginRight="10dp"
android:adjustViewBounds="true"
android:padding="10dp"
android:background="@drawable/border">

<ImageView
    android:id="@+id/logo"
    android:layout_width="70dp"
    android:layout_height="70dp"
    app:srcCompat="@drawable/rsz_honda_bike" />

<TextView
    android:id="@+id/name"
    android:textStyle="bold"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="TextView"
    android:textColor="@android:color/black"
    android:textSize="15sp"
    android:layout_gravity="center"/>
</LinearLayout>
相关问题