52.11 Adding an Action to the Snackbar
The final task in this project is to add an action to the Snackbar that allows the user to undo the most recent addition to the list. Edit the MainActivity.kt file and modify the Snackbar creation code to add an action titled “Undo” configured with an onClickListener named undoOnClickListener:
findViewById<FloatingActionButton>(R.id.fab).setOnClickListener { view ->
addListItem()
Snackbar.make(view, "Item added to list", Snackbar.LENGTH_LONG)
.setAction("Undo", undoOnClickListener).show()
}
Within the MainActivity.kt file add the listener handler:
var undoOnClickListener: View.OnClickListener = View.OnClickListener { view ->
listItems.removeAt(listItems.size - 1)
adapter?.notifyDataSetChanged()
...