适配器中的 notifyDataSetChanged() 似乎不起作用

notifyDataSetChanged() in Adapter doesn't seem to work

我的 recyclerView 中有一个删除按钮。单击该按钮时,用户可以根据位置删除它。之后我希望 recyclerView 更新。我在我的适配器中添加了以下代码 class 但它仍然不起作用。

 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()
        }
    }

您没有从列表中删除项目,这就是 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)

您必须从列表中删除所选项目,然后通知适配器。

请试试这个代码:

yourDataset.removeAt(position);
notifyItemRemoved(position);
notifyItemRangeChanged(position, yourDataset.size()); //If needed

希望这些步骤能帮助您从回收站视图中删除项目。