我,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
后,布局管理器会重新排序一些项目以填补空白(这很好,我想要这种行为),但是如果某项目从第二列移动到第一列,它将不使用上面代码中为第一列定义的边距,并且如果项目从第一列移到第二列,则不会再更新其边距。如何解决这种不当行为?
答案 0 :(得分:0)
以下解决方案很有魅力!
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();
}
}