我使用GridLayoutManager
覆蓋getItemOffsets()
方法(請參閱下面的代碼)將等於邊距應用於我的RecyclerView
。ItemDecoration覆蓋getItemOffsets()和動畫
但是,當從適配器中刪除一個對象時,將不調用偏移量來調用刪除動畫。因此,迴歸開始於與要移除的對象不同的位置。
我試圖通過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);
}
請您在移除物品時澄清您的問題嗎?如果你刪除一個元素,下一個元素動畫來填充空的位置,這究竟是不是工作? –
對於RecyclerView中的元素,偏移量顯示正確(例如,最後一列中的元素左側20個像素,右側40個像素右側)。使用上面的代碼時,動畫由於位置== RecyclerView.NO_POSITION'而從方法返回,因此在沒有邊距的位置(0左和0右)開始。在這裏,我需要找出已刪除元素的位置(例如最後一列),以便爲平滑動畫應用正確的偏移量。 –