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:
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)
}
private var onItemDeletedListener: OnItemDeletedListener? = null
fun setOnItemDeletedListener(listener: OnItemDeletedListener) {
onItemDeletedListener = listener
}
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
}
}
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.