1 回答

TA貢獻1810條經驗 獲得超5個贊
我可以在上面的代碼中看到 2 個問題,
當我們添加和刪除時您正在更新數據庫,這很好,但是您處理本地視圖引用的方式是錯誤的。
原因:因為在你的情況下,不僅當你轉到另一個屏幕時它不會工作,如果你滾動更多如果你有更多的項目然后回來它也不會工作,因為回收視圖重用你更新的視圖在檢查監聽器中,這導致了第二個問題
在 onBindData 中,你總是應該使用非收藏圖標,所以每當你滾動和查看重用它時,它只會顯示非收藏圖標,你應該檢查該項目是否是收藏,你應該更新視圖
例如,你應該像下面那樣
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
}
}
請根據您的項目修改代碼。
添加回答
舉報