You need to enable JavaScript to run this app. ItemTouchHelper侧滑删除RecyclerView抛出UnsupportedOperationException
优惠活动
大模型
产品
解决方案
定价
更多

ItemTouchHelper侧滑删除RecyclerView抛出UnsupportedOperationException

报错核心原因

你碰到的java.lang.UnsupportedOperationException,根源是初始化RecyclerView数据源时,Arrays.asList()返回的List是固定长度的数组包装对象,不支持元素增、删操作,仅支持按索引修改元素内容。
为什么两个拖拽/滑动操作表现不一致:

  • onMove()里调用Collections.swap(studentList, currentPosition, targetPosition),本质是按索引交换两个位置的元素值,全程不会改变List的长度,完全适配Arrays.asList()返回对象的能力范围,所以拖动交换条目可以正常运行。
  • onSwiped()里调用studentList.remove(),是要删除元素、改变List长度的操作,这个包装类本身没有实现remove方法,最终走到父类AbstractList的默认空实现,就直接抛出了你贴出的异常堆栈。
修复方案

只需要把Fragment里初始化测试数据的不可变List,替换为支持增删操作的可变ArrayList即可,不需要修改适配器、ItemTouchHelper回调里的任何逻辑:
将原来的初始化代码:

// 原代码:返回的是固定长度的不可变List
List<Student> students = Arrays.asList(
        new Student("Ahmad", 1, R.drawable.profile, "PASS"),
        new Student("Mahmood", 2, R.drawable.profile, "FAIL"),
        new Student("Zakir", 3, R.drawable.profile, "PASS"),
        new Student("Rezaq", 8, R.drawable.profile, "FAIL"),
        new Student("Zeya", 9, R.drawable.profile, "FAIL"),
        new Student("Rasool", 10, R.drawable.profile, "FAIL"),
        new Student("Parwiz", 11, R.drawable.profile, "FAIL")
);

改为用ArrayList包装一层,获得完整的增删能力:

// 新代码:返回支持增删改的可变ArrayList
List<Student> students = new ArrayList<>(Arrays.asList(
        new Student("Ahmad", 1, R.drawable.profile, "PASS"),
        new Student("Mahmood", 2, R.drawable.profile, "FAIL"),
        new Student("Zakir", 3, R.drawable.profile, "PASS"),
        new Student("Rezaq", 8, R.drawable.profile, "FAIL"),
        new Student("Zeya", 9, R.drawable.profile, "FAIL"),
        new Student("Rasool", 10, R.drawable.profile, "FAIL"),
        new Student("Parwiz", 11, R.drawable.profile, "FAIL")
));
补充优化建议

修改完数据源类型后,建议给onSwiped()里的位置取值加上有效性判断,避免快速滑动时Adapter返回无效位置(即RecyclerView.NO_POSITION)引发数组越界异常:

@Override
public void onSwiped(@NonNull RecyclerView.ViewHolder viewHolder, int direction) {
    int swipedPosition = viewHolder.getAdapterPosition();
    // 位置无效时直接终止逻辑,避免崩溃
    if (swipedPosition == RecyclerView.NO_POSITION) return;
    studentList.remove(swipedPosition);
    notifyItemRemoved(swipedPosition);
}

内容的提问来源于stack exchange,提问作者Sayed Naweed

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.11.05 14:24:04