如何在 android 中减少回收器视图(GridLayoutManager)中列之间的 space

How to reduce space between columns in recycler view(GridLayoutManager) in android

我正在使用 Recyclerview 的 GridLayoutManager 在我的应用程序中显示自定义图库。我已经实现了画廊等所有功能。但是我坚持了一件小事。在一行中,我有 3 张图片。但是我需要减少图像之间的 space 。这样做时,我不想连续显示超过 3 张图像,但图像大小(如果需要)可以增加。

将其用于回收站视图,

    this.mRecyclerView.setLayoutManager(new GridLayoutManager(getContext(), 3));
    this.mRecyclerView.addItemDecoration(new HorizontalDividerItemDecoration.Builder(getContext())
            .color(Color.DKGRAY)
            .build());
    this.mRecyclerView.addItemDecoration(new VerticalDividerItemDecoration.Builder(getContext())
            .color(Color.DKGRAY)
            .build());

并在每个项目的布局文件中,以符合容器边缘的方式设置图像。

例如:

<RelativeLayout
  xmlns:android="http://schemas.android.com/apk/res/android"
  android:id="@+id/RlayoutGrid"
  android:layout_width="220dp"
  android:layout_height="170dp"
  android:background="@android:color/black">


    <ImageView
      android:id="@+id/prefence_imageButton"
      android:layout_width="match_parent"
      android:layout_height="170dp"
      android:background="@android:color/black"
      android:focusable="false"
      android:focusableInTouchMode="false"
      android:scaleType="fitXY"
      />

</RelativeLayout>

并将其添加到您的 build.gradle

 compile 'com.yqritc:recyclerview-flexibledivider:1.2.4'

您可以使用自定义 RecyclerViewItemDecorator:

public class RecyclerViewItemDecorator extends RecyclerView.ItemDecoration {
  private int spaceInPixels;

  public RecyclerViewItemDecorator(int spaceInPixels) {
    this.spaceInPixels = spaceInPixels;
  }

  @Override
  public void getItemOffsets(Rect outRect, View view, 
      RecyclerView parent, RecyclerView.State state) {
    outRect.left = spaceInPixels;
    outRect.right = spaceInPixels;
    outRect.bottom = spaceInPixels;

    if (parent.getChildLayoutPosition(view) == 0) {
        outRect.top = spaceInPixels;
    } else {
        outRect.top = 0;
    }
  }
}

然后将其添加到您的 RecyclerView:

// For example 10 pixels
int spaceInPixels = 10;
mRecyclerView.addItemDecoration(new RecyclerViewItemDecorator(spaceInPixels));

希望对您有所帮助!

要删除间距,您可以使用 outRect.setEmpty()

RecyclerView.ItemDecoration divider = new RecyclerView.ItemDecoration(){
    @Override
    public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
        outRect.setEmpty();
    }
};
grid.addItemDecoration(divider);