Ask Your Question
0

How to inform RecyclerView adapter in Android with Kotlin whenever an item is deleted using the popup menu on item?

asked 2023-07-13 14:05:19 +0000

david gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
0

answered 2023-07-13 14:07:02 +0000

lalupa gravatar image

To inform the RecyclerView adapter in Android with Kotlin whenever an item is deleted using the popup menu on item, you can follow these steps:

  1. Add an interface in your RecyclerView adapter class (e.g. ItemAdapter) to handle the callback when an item is deleted. This interface will have a method onItemDeleted(position: Int) which takes the position of the deleted item as a parameter.
interface OnItemDeletedListener {
    fun onItemDeleted(position: Int)
}
  1. Create a variable of this interface type in your adapter class.
private var onItemDeletedListener: OnItemDeletedListener? = null
  1. Add a public method to set the listener for this interface.
fun setOnItemDeletedListener(listener: OnItemDeletedListener) {
    onItemDeletedListener = listener
}
  1. In your RecyclerView.ViewHolder, set a listener for the delete action on the popup menu.
popupMenu.setOnMenuItemClickListener { menuItem ->
    when (menuItem.itemId) {
        R.id.action_delete -> {
            onItemDeletedListener?.onItemDeleted(adapterPosition)
            true
        }
        else -> false
    }
}
  1. Set the listener for the adapter in your Activity or Fragment.
itemAdapter.setOnItemDeletedListener(object : ItemAdapter.OnItemDeletedListener {
    override fun onItemDeleted(position: Int) {
        // Delete the item from your data source
        items.removeAt(position)
        // Notify the adapter that an item has been removed
        itemAdapter.notifyItemRemoved(position)
    }
})

After following these steps, whenever the delete action is triggered on the popup menu, the onItemDeleted() method will be called in the adapter, which will delete the item from the data source, and notify the adapter with notifyItemRemoved(), removing the item from the RecyclerView.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2023-07-13 14:05:19 +0000

Seen: 12 times

Last updated: Jul 13 '23