A Snackbar is a useful little panel that pops up at the bottom of the screen to display a short piece of feedback to the user. It can either persist until dismissed by the user or show for a set amount of time. Snackbars can also display an optional button to trigger an action when tapped.
Earlier in the tutorial, you added a Simple Dialog to let the user add a fruit item. You might remember that you replaced setItems() when you added the Confirmation Dialog. Now, you’ll revert this to show the Simple Dialog again.
Replace the following code in showAddFruitDialog():
.setNeutralButton(resources.getString(R.string.dialog_cancel)) { dialog, _ ->
dialog.cancel()
}
.setPositiveButton(resources.getString(R.string.dialog_add_fruit_positive_button))
{ dialog, _ ->
checkedItems.forEachIndexed { fruitItem, isChecked ->
if (isChecked) updateFruitQuantity(fruitItem, true)
}
dialog.dismiss()
}
.setMultiChoiceItems(fruitItems, checkedItems) { _, position, checked ->
checkedItems[position] = checked
}
with these lines:
.setItems(fruitItems) { dialog, selectedFruitItem ->
updateFruitQuantity(selectedFruitItem, true)
dialog.dismiss()
showSnackbar(selectedFruitItem)
}
As you can remember, the item click listener is already set up to call showSnackbar().
Adding a Snackbar
When the user selects fruit from the dialog, the dialog closes and the quantity gets updated. It’s possible the user might not notice the quantity value changing or might accidentally tap the wrong type of fruit. In both of these cases, a Snackbar can provide information and assurance to the user by displaying feedback in the form of a confirmation message and providing an “undo” action.
Now, open MainActivity.kt and find showSnackbar().
Replace TODO in showSnackbar() with the following:
val snackbarText = getString(R.string.snackbar_fruit_added, fruitItems[selectedFruitItem])
Snackbar.make(layout_main, snackbarText, Snackbar.LENGTH_LONG)
.setAction(R.string.snackbar_undo) {
updateFruitQuantity(selectedFruitItem, false)
}
.show()
First, this code creates the string value snackbarText. Here, it uses the position of the selected fruit item from the dialog to get the name from the list of fruits. This name is then inserted into the string resource value for the Snackbar to display.
Snackbar.make() creates a Snackbar with a parent view from which the Snackbar can find an ancestor ViewGroup in which to display itself, the text to be displayed and how long to display it. There are three default options: LENGTH_LONG, LENGTH_SHORT and LENGTH_INDEFINITE.
In this case, you want to show an undo action. setAction() takes the string for the button, and a click listener which resets the previously updated fruit quantity value.
Finally, show() displays the Snackbar on the screen. Build and run. Tap Add fruit and select a fruit item from the dialog. The Snackbar appears at the bottom of the screen. If you tap undo, you’ll see the quantity numbers reduce accordingly.