我正在使用GridLayoutManager
覆盖getItemOffsets()
方法,为我的RecyclerView
应用相等的间距(请参见下面的代码)。
然而,当适配器中的一个对象被移除时,删除动画会在没有偏移量的情况下调用。因此,动画开始的位置与要删除的对象不同。
我尝试通过getSpanIndex(position)
获取位置,但是当getItemOffsets()
被调用时,由于该对象已从适配器中移除,因此位置(parent.getChildAdapterPosition(view)
)返回NO_POSITION
。
在我的情况下,有没有办法获得偏移量?
@Override
public void getItemOffsets(Rect outRect, View view,
RecyclerView parent, RecyclerView.State state) {
GridLayoutManager mgr = parent.getLayoutManager();
int position = parent.getChildAdapterPosition(view);
if (position == RecyclerView.NO_POSITION) {
// here I need to access the position of the current element
// and call outRect.set(left, top , right, bottom);
// which is not possible because it is no longer in the adapter
return;
}
int spanCount = mgr.getSpanCount();
int spanSize = mgr.getSpanSizeLookup().getSpanSize(position);
int spanIndex = mgr.getSpanSizeLookup().getSpanIndex(position, spanCount);
if (spanIndex == spanCount-1) {
// last element
left = space / 2;
right = space;
} else if (spanIndex == 0) {
// first element
left = space;
right = space / 2;
} else {
// middle element
left = space / 2;
right = space / 2;
}
outRect.set(left, top, right, bottom);
}
position == RecyclerView.NO_POSITION
,因此动画从没有边距的位置(0左侧和0右侧)开始。在这里,我需要找出删除元素的位置(例如,最后一列),以应用正确的偏移量以实现平滑动画。 - jeff_bordon