Visual Feedback: Dialogs, Snackbars & Toasts

Mar 16 2021 Kotlin 1.4, Android 11, Android Studio 4

Part 1: Visual Feedback: Dialogs, Snackbars & Toasts

7. Use Snackbars

Lesson Complete

Play Next Lesson
Next
Save for later
About this episode
See forum comments
Cinema mode Mark as Complete Download course materials
Previous episode: 6. Use Progress Indicators Next episode: 8. Create & Display Toasts

This video was last updated on Mar 16 2021

Heads up... You've reached locked video content where the transcript will be shown as obfuscated text.

You can unlock the rest of this video course, and our entire catalogue of books and videos, with a kodeco.com Professional subscription.

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.

.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
    }
.setItems(fruitItems) { dialog, selectedFruitItem ->
     updateFruitQuantity(selectedFruitItem, true)
     dialog.dismiss()
     showSnackbar(selectedFruitItem)
   }

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.

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()