【问题标题】:StaggeredGridLayoutManager reorders items without respecting to defined marginsStaggeredGridLayoutManager 重新排序项目而不考虑定义的边距
【发布时间】:2020-05-01 23:10:54
【问题描述】:

我',将StaggeredGridLayoutManager 用于我的RecyclerView,以便在两列中显示宽度相同但高度不同的项目。因为我希望项目之间的差距相等,所以使用了以下ItemDecoration

public class ImageCardDecoration extends RecyclerView.ItemDecoration {
    private int margin;

    public ImageCardDecoration(Context context) {
        margin = 5;
    }

    @Override
    public void getItemOffsets(@NonNull Rect outRect, @NonNull View view, @NonNull RecyclerView parent, @NonNull RecyclerView.State state) {
        super.getItemOffsets(outRect, view, parent, state);

        int position = parent.getChildAdapterPosition(view);
        int spanIndex =((StaggeredGridLayoutManager.LayoutParams)view.getLayoutParams()).getSpanIndex();
        if (spanIndex == 0) {
            outRect.left = 2 * margin;
            outRect.right = margin;
        } else {
            outRect.left = margin;
            outRect.right = 2 * margin;
        }
        outRect.top = 2 * margin;

        if (position == 0 || position == 1)
            outRect.top = 14 * margin;
    }
}

而且效果很好。但是在滚动recyclerview并且当它得到Idle之后,布局管理器重新排序一些项目以填补空白(这很好,我想要这种行为),但是如果一个项目从第二列移动到第一列,它不会' t 使用上述代码中为第一列定义的边距,并且如果项目从第一列移动到第二列,它也不会更新其边距。如何解决这种不当行为?!

【问题讨论】:

    标签: android android-layout android-recyclerview staggeredgridlayoutmanager


    【解决方案1】:

    以下解决方案非常有效!

            recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(@NonNull final RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
    
                if (newState == RecyclerView.SCROLL_STATE_IDLE)
                    recyclerView.invalidateItemDecorations();
            }
    }
    

    【讨论】:

      猜你喜欢
      • 2017-06-16
      • 2017-12-16
      • 1970-01-01
      • 1970-01-01
      • 2021-08-13
      • 1970-01-01
      • 1970-01-01
      • 2013-04-25
      • 2014-12-20
      相关资源
      最近更新 更多