Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

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.