RecyclerView notifyItemRemoved IllegalStateException解决方案

项目中,我在列表的长按删除调用notifyItemRemoved方法时遇到了IllegalStateException,一开始按照网上的解决方案,在notifyItemRemoved()后调用notifyItemRangeChanged(),但是不行

            mDataList.remove(i);
            notifyItemRemoved(position);
            notifyItemRangeChanged(position, mDataList.size() - position);

通过调试发现出现问题时recyclerView.isComputingLayout() 一直是true,即使用postDelayed(100)来递归延时调用还是一直处于isComputingLayout()==true ,而且延迟处理也不是我希望的解决方式,但是不加notifyItemRangeChanged,又会出现大家经常遇到的删除错乱,改用notifyDataSetChanged()取消动画效果我更不甘心,于是开始考虑在不执行notifyItemRangeChanged()的情况下删除正确item的解决方式。
于是我尝试把ViewHolder的AdapterPosition传给notifyItemRemoved(),以保证删除的是执行长按的item,同时不根据索引,而是直接传入itemData对象来删除目标数据,来解决删除错乱。

       if (mDataList.remove(data)) {
           notifyItemRemoved(position);
       }

经过测试,很好的解决了IllegalStateException异常,也不会出现删除错乱的问题

你可能感兴趣的:(RecyclerView notifyItemRemoved IllegalStateException解决方案)