为RecyclerView设置了ItemDecorations
之后,在Adapter刷新数据notifyDataSetChanged
后,item的间距会不断增大。
原因:
recyclerView.addItemDecoration()方法中mItemDecorations并没有clear,每次都会添加进去,导致间距不断变大。
public void addItemDecoration(ItemDecoration decor, int index) {
if (mLayout != null) {
mLayout.assertNotInLayoutOrScroll("Cannot add item decoration during a scroll or"
+ " layout");
}
if (mItemDecorations.isEmpty()) {
setWillNotDraw(false);
}
if (index < 0) {
mItemDecorations.add(decor);
} else {
mItemDecorations.add(index, decor);
}
markItemDecorInsetsDirty();
requestLayout();
}
解决方法:
- 1.清除添加的ItemDecorations
recyclerView.removeItemDecoration();
- 2.判断是否已经添加了ItemDecorations,如果存在就不添加
if (recyclerView.getItemDecorationCount() == 0) {
recyclerView.addItemDecoration(new SpacesItemDecoration2(50, 20));
}
通过上述两种方式可以解决Item间距刷新后不断增加的问题。