我的recyclerView
中有一个删除按钮。单击按钮后,用户可以根据位置将其删除。之后,我想更新recyclerView
。我在适配器类中添加了以下代码,但仍然无法正常工作。
notifyItemRemoved(position)
notifyDataSetChanged()
适配器
holder.mDeleteImage.setOnClickListener {
val builder = AlertDialog.Builder(context)
// Set the alert dialog title
builder.setTitle("Delete Item")
// Display grid_item message on alert dialog
builder.setMessage("Are you want to delete this item ?")
// Display grid_item negative button on alert dialog
builder.setNegativeButton("No") { dialog, which ->
dialog.dismiss()
}
// Set grid_item positive button and its click listener on alert dialog
builder.setPositiveButton("YES") { dialog, which ->
var dialog = Util().callDialog(context)
GlobalScope.launch(Dispatchers.Main) {
val service = RetrofitFactory.makeRetrofitService()
service.delete(item.id)
}
val handler = Handler()
handler.postDelayed(Runnable {
dialog.dismiss()
notifyItemRemoved(position)
notifyDataSetChanged()
context.longToast("Done")
}, 5000)
}
// Finally, make the alert dialog using builder
val dialog: AlertDialog = builder.create()
// Display the alert dialog on app interface
dialog.show()
}
}
答案 0 :(得分:3)
您没有从列表中删除项目,这就是notifyItemRemoved(position)
的原因
并且notifyDataSetChanged()
无法正常工作
进行以下代码更改
handler.postDelayed(Runnable {
dialog.dismiss()
// remove here item from yourlist then use notifyItemRemoved(position)
arrayList.removeAt(position)
notifyItemRemoved(position)
//notifyDataSetChanged() // Is not necessary.
context.longToast("Done")
}, 5000)
答案 1 :(得分:3)
您必须从列表中删除选定的项目,然后通知适配器。
请尝试以下代码:
yourDataset.removeAt(position);
notifyItemRemoved(position);
notifyItemRangeChanged(position, yourDataset.size()); //If needed
希望此步骤将帮助您从“回收者”视图中删除项目。