StaggeredGridLayoutManager 重新排序项目而不考虑定义的边距

StaggeredGridLayoutManager reorders items without respecting to defined margins

I',将 StaggeredGridLayoutManager 用于我的 RecyclerView,以便在 2 列中显示宽度相同但高度不同的项目。因为我希望项目之间的间距相等,所以使用了以下 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 时,布局管理器重新排序一些项目以填补空白(这很好,我想要这种行为),但是如果一个项目从第二列移动到第一列,它不使用上面代码中为第一列定义的边距,而且如果项目从第一列移动到第二列,它也不会更新其边距。如何解决这种不当行为?!

以下解决方案非常有效!

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