簡體   English   中英

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

[英]notifyDataSetChanged() in Adapter doesn't seem to work

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

您沒有從列表中刪除項目,這就是為什么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

希望此步驟將幫助您從“回收者”視圖中刪除項目。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM