android 使用 itemTouchHelper 拖放导致 IndexOutOfBoundsException
android drag&drop with itemTouchHelper causes IndexOutOfBoundsException
我正在使用 itemTouchHelper 来拖动&drop/swipe-to-delete 我的 RecyclerView 列表 as described here 中的项目。这些项目 switched/deleted 没有问题,但是由于列表项目上的按钮是在调用 onBindViewHolder 时创建的,所以按钮 "remember" 的 POSITION 没有更新,这会导致很多错误(主要是 IndexOutOfBound例外)。请帮忙,我无法让它工作。
例如,假设我在列表中有 2 个项目,A 和 B。
然后,我在它们之间切换以获得 B 和 A。
然后,我单击 B 上的复选框(这会立即更新服务器)。
当我查看服务器时,A 有一个选中的复选框,而不是 B(即使我点击了 B),因为调用时位置没有更新:
mValues.get(position).put("checkbox",true)
代码如下:
@Override
public boolean onItemMove(int fromPosition, int toPosition) {
if (fromPosition < toPosition) {
for (int i = fromPosition; i < toPosition; i++) {
Collections.swap(mValues, i, i + 1);
notifyItemMoved(i, i + 1);
}
} else {
for (int i = fromPosition; i > toPosition; i--) {
Collections.swap(mValues, i, i - 1);
notifyItemMoved(i, i-1);
}
}
return true;
}
和:
@Override
public void onItemDismiss(int position) {
if (mValues.size() > position) {
mValues.remove(position).deleteEventually();
notifyItemRemoved(position);
}
}
the POSITION that the button "remember" is not updated,
与 ListView 适配器等中使用的视图 "remembering" 位置策略不同,RecyclerView 需要不同的方法。
有关示例解决方案,请参阅 this SO answer。
我正在使用 itemTouchHelper 来拖动&drop/swipe-to-delete 我的 RecyclerView 列表 as described here 中的项目。这些项目 switched/deleted 没有问题,但是由于列表项目上的按钮是在调用 onBindViewHolder 时创建的,所以按钮 "remember" 的 POSITION 没有更新,这会导致很多错误(主要是 IndexOutOfBound例外)。请帮忙,我无法让它工作。
例如,假设我在列表中有 2 个项目,A 和 B。 然后,我在它们之间切换以获得 B 和 A。 然后,我单击 B 上的复选框(这会立即更新服务器)。 当我查看服务器时,A 有一个选中的复选框,而不是 B(即使我点击了 B),因为调用时位置没有更新:
mValues.get(position).put("checkbox",true)
代码如下:
@Override
public boolean onItemMove(int fromPosition, int toPosition) {
if (fromPosition < toPosition) {
for (int i = fromPosition; i < toPosition; i++) {
Collections.swap(mValues, i, i + 1);
notifyItemMoved(i, i + 1);
}
} else {
for (int i = fromPosition; i > toPosition; i--) {
Collections.swap(mValues, i, i - 1);
notifyItemMoved(i, i-1);
}
}
return true;
}
和:
@Override
public void onItemDismiss(int position) {
if (mValues.size() > position) {
mValues.remove(position).deleteEventually();
notifyItemRemoved(position);
}
}
the POSITION that the button "remember" is not updated,
与 ListView 适配器等中使用的视图 "remembering" 位置策略不同,RecyclerView 需要不同的方法。
有关示例解决方案,请参阅 this SO answer。