項(xiàng)目中,我在列表的長按刪除調(diào)用notifyItemRemoved方法時(shí)遇到了IllegalStateException它褪,一開始按照網(wǎng)上的解決方案健无,在notifyItemRemoved()后調(diào)用notifyItemRangeChanged()苛让,但是不行
mDataList.remove(i);
notifyItemRemoved(position);
notifyItemRangeChanged(position, mDataList.size() - position);
通過調(diào)試發(fā)現(xiàn)出現(xiàn)問題時(shí)recyclerView.isComputingLayout()
一直是true弄贿,即使用postDelayed(100)來遞歸延時(shí)調(diào)用還是一直處于isComputingLayout()==true
春锋,而且延遲處理也不是我希望的解決方式,但是不加notifyItemRangeChanged差凹,又會(huì)出現(xiàn)大家經(jīng)常遇到的刪除錯(cuò)亂期奔,改用notifyDataSetChanged()
取消動(dòng)畫效果我更不甘心,于是開始考慮在不執(zhí)行notifyItemRangeChanged()
的情況下刪除正確item的解決方式危尿。
于是我嘗試把ViewHolder的AdapterPosition傳給notifyItemRemoved()呐萌,以保證刪除的是執(zhí)行長按的item,同時(shí)不根據(jù)索引谊娇,而是直接傳入itemData對(duì)象來刪除目標(biāo)數(shù)據(jù)肺孤,來解決刪除錯(cuò)亂。
if (mDataList.remove(data)) {
notifyItemRemoved(position);
}
經(jīng)過測(cè)試邮绿,很好的解決了IllegalStateException異常渠旁,也不會(huì)出現(xiàn)刪除錯(cuò)亂的問題