如何在安卓中的Recycler View(GridLayoutManager)中减少列之间的间距

3
我正在使用recyclerview的GridLayoutManager来显示自定义画廊。我已经实现了所有画廊的功能,但是有一个小问题困扰着我。在一行中,我有3张图片。但是我需要减少图像之间的间距。在这样做时,我不想在一行中显示超过3张图片,但如果需要,图像大小可以增加。

1
这可能会对你有所帮助:https://dev59.com/E14b5IYBdhLWcg3w7Fcv - H Raval
谢谢,我尝试过了,但第一张图片视图的顶部没有添加空间。而最后一个视图则添加了额外的空间。此外,水平和垂直间距也不均匀。 - D Agrawal
请在此处添加图片,用于展示现状和您的期望。 - Gundu Bandgar
3个回答

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));

希望能帮到你!

1
使用此代码来实现RecyclerView:
    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'

它说,无法解析HorizontalDividerItemDecoration.Builder和VerticalDividerItemDecoration.Builder。 - D Agrawal
@DAgrawal,您忘记添加依赖项了。是的,我是个死灵贴。 - 0neel

0

为了去除间距,您可以使用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);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接