如何在android中的recycleler视图(GridLayoutManager)中减少列之间的空间

时间:2016-03-28 06:28:07

标签: android android-layout android-recyclerview gridlayoutmanager

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

3 个答案:

答案 0 :(得分:3)

您可以使用自定义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 :(得分:0)

将此用于回收者视图

    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'

答案 2 :(得分: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);