Android RecyclerView GridLayoutManager更改项目高度会在列之间创建空格

时间:2017-05-16 10:13:54

标签: java android android-recyclerview

我有一个带水平GridLayoutManager的RecyclerView。在我的应用程序中,可以更改列高。如果我增加列的高度,一切都按预期工作: 之前: before 后: after 但如果我减少列的高度,则显示一个空白区域: space

cell xml:

<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/one_day_linearLayout"
android:layout_width="match_parent"
android:layout_height="200dp"
android:minHeight="200dp"
>

<android.support.v7.widget.RecyclerView
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/one_day_recyclerView"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_margin="2dp"
    android:background="@color/colorAccent"
   />

我正在ViewHolders上直接更改高度。如何删除列之间的空格?

1 个答案:

答案 0 :(得分:0)

RecyclerViews支持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;
    }
  }
}