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

问题描述 投票:1回答:2

我的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()
        }
    }
android kotlin android-recyclerview notifydatasetchanged
2个回答
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)

4
投票

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

请尝试以下代码:

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

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

© www.soinside.com 2019 - 2024. All rights reserved.