1 回答
TA貢獻(xiàn)1810條經(jīng)驗(yàn) 獲得超5個(gè)贊
我可以在上面的代碼中看到 2 個(gè)問(wèn)題,
當(dāng)我們添加和刪除時(shí)您正在更新數(shù)據(jù)庫(kù),這很好,但是您處理本地視圖引用的方式是錯(cuò)誤的。
原因:因?yàn)樵谀愕那闆r下,不僅當(dāng)你轉(zhuǎn)到另一個(gè)屏幕時(shí)它不會(huì)工作,如果你滾動(dòng)更多如果你有更多的項(xiàng)目然后回來(lái)它也不會(huì)工作,因?yàn)榛厥找晥D重用你更新的視圖在檢查監(jiān)聽(tīng)器中,這導(dǎo)致了第二個(gè)問(wèn)題
在 onBindData 中,你總是應(yīng)該使用非收藏圖標(biāo),所以每當(dāng)你滾動(dòng)和查看重用它時(shí),它只會(huì)顯示非收藏圖標(biāo),你應(yīng)該檢查該項(xiàng)目是否是收藏,你應(yīng)該更新視圖
例如,你應(yīng)該像下面那樣
override fun onBindViewHolder(holder: VM, position: Int) {
val item = items.get(position)
if (item.favourite == 0) {
holder.name.text = item.name
} else {
holder.name.text = item.name + " Liked "
}
holder.favouriteIcon.setOnCheckedChangeListener { compoundButton, isChecked ->
// Should not update local view reference here
if(isChecked) {
// Update the local reference object, Just not to update from DB
item.favourite = 1
// Do the logic to update the DB to add the item in Fav
} else {
// Update the local reference object, Just not to update from DB
item.favourite = 0
// Do the logic to update to remove the item from Fav list
}
notifyItemChanged(position) // Helps to update the particular item
}
}
請(qǐng)根據(jù)您的項(xiàng)目修改代碼。
添加回答
舉報(bào)
