【问题标题】:android drag&drop with itemTouchHelper causes IndexOutOfBoundsExceptionandroid 拖放与 itemTouchHelper 导致 IndexOutOfBoundsException
【发布时间】:2015-11-13 09:09:07
【问题描述】:

我正在使用 itemTouchHelper 拖放/滑动删除我的 RecyclerView 列表as described here 中的项目。项目被切换/删除没有问题,但由于列表项目上的按钮是在调用 onBindViewHolder 时创建的,所以按钮“记住”的 POSITION 没有更新,这会导致很多错误(主要是 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);
        }
    }

【问题讨论】:

    标签: android android-recyclerview indexoutofboundsexception


    【解决方案1】:

    “记住”按钮没有更新的位置,

    与在例如 ListView 适配器中使用的视图“记住”位置的策略不同,RecyclerView 需要一种不同的方法。

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

    【讨论】:

      猜你喜欢
      • 2017-01-13
      • 2019-10-23
      • 1970-01-01
      • 2016-05-18
      • 1970-01-01
      • 2015-01-27
      • 1970-01-01
      • 2019-11-30
      • 1970-01-01
      相关资源
      最近更新 更多