android drag& drop with itemTouchHelper导致IndexOutOfBoundsException

时间:2015-08-19 21:43:06

标签: android android-recyclerview indexoutofboundsexception

我正在使用itemTouchHelper在我的RecyclerView列表as described here中拖放/删除/滑动删除项目。项目被切换/删除没有问题,但由于列表项上的按钮是在调用onBindViewHolder时创建的,因此按钮“记住”的位置不会更新,并且会导致许多错误(主要是IndexOutOfBound异常)。请帮助,我无法让它工作。

例如,假设列表中有2个项目,A和B. 然后,我在它们之间切换以获得B和A. 然后,我点击B上的CheckBox(立即更新服务器)。 当我查看服务器时,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);
        }
    }

1 个答案:

答案 0 :(得分:1)

  

按钮&#34;记住的位置&#34;没有更新,

不同于观点策略&#34;记住&#34;在例如ListView适配器中使用的位置,在RecyclerView中需要不同的方法。

有关示例解决方案,请参阅this SO answer