版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_31876841/article/details/88354260
StraggeredGridLayoutManager 边距错乱
问题发生在我把 RecyclerView
的 LinearLayoutManager
换成了 StaggeredGridLayoutManager
后,Item 的边距发生了错落,和预想的不一样。这是因为瀑布流的item不是根据下标的顺序去排列,而是根据上方的两个item的高度差确定位置。
解决方案
我们只要在 ItemDecoration
中通过 StaggeredGridLayoutManager
的 getSpanIndex()
方法,获取当前 item 的位置,再设置边距就可以了。
recyclerView.addItemDecoration(new ItemDecoration() {
@Override
public void getItemOffsets(Rect outRect, View view, RecyclerView parent, State state) {
StaggeredGridLayoutManager.LayoutParams layoutParams = (LayoutParams) view
.getLayoutParams();
int spanIndex = layoutParams.getSpanIndex();
if (spanIndex == 0) {
outRect.left = SizeUtil.dp2px(12);
outRect.right = SizeUtil.dp2px(6);
} else {
outRect.left = SizeUtil.dp2px(6);
outRect.right = SizeUtil.dp2px(12);
}
outRect.top = SizeUtil.dp2px(12);
}
});