Skip to main content
Android Development with Kotlin
CHAPTER 17 Beginner

State Management with ViewModel

Updated: May 16, 2026
30 min read

# Chapter 17: Dialogs, Snackbars, and Toasts

1. Introduction

When building mobile applications, communicating with the user without completely leaving the current screen is essential. Whether it's a brief success message, an undo action, or a critical confirmation prompt, Android provides three primary mechanisms for temporary UI feedback: Toasts, Snackbars, and Dialogs.

2. Learning Objectives

By the end of this chapter, you will be able to:
  • Display short, non-interactive messages using Toast.
  • Implement interactive, temporary notifications using Snackbar.
  • Create and customize modal alert boxes using AlertDialog.
  • Understand when to use which feedback mechanism based on UX best practices.

3. Core Concepts & Implementation

Toasts

A Toast is a simple popup message that appears near the bottom of the screen. It is non-blocking (users can continue interacting with the app) and disappears automatically.

Use Case: Simple feedback, like "Draft saved."

kotlin
12
// Syntax: Toast.makeText(context, text, duration).show()
Toast.makeText(this, "Profile updated successfully!", Toast.LENGTH_SHORT).show()

*Note: The duration can be Toast.LENGTH_SHORT (approx 2 seconds) or Toast.LENGTH_LONG (approx 3.5 seconds).*

Snackbars

Introduced with Material Design, Snackbar is a modern alternative to Toast. It appears at the bottom of the screen, can contain a single action (like "UNDO"), and can be swiped away by the user.

Use Case: Feedback that might require a quick user action, like "Item deleted [UNDO]".

To use Snackbar, you need the Material Components library (included by default in modern Android projects).

kotlin
12345678910111213141516
import com.google.android.material.snackbar.Snackbar

// myRootLayout is the parent view of your activity/fragment
val snackbar = Snackbar.make(
    findViewById(R.id.myRootLayout), 
    "Item removed from cart", 
    Snackbar.LENGTH_LONG
)

// Adding an optional action
snackbar.setAction("UNDO") {
    // Logic to restore the item
    restoreItem()
}

snackbar.show()

AlertDialogs

An AlertDialog is a modal window that overlays the screen. It demands the user's attention and requires them to make a choice or acknowledge a message before continuing.

Use Case: Destructive actions (e.g., "Are you sure you want to delete your account?") or requiring explicit user choice.

kotlin
1234567891011121314151617181920212223242526272829
import androidx.appcompat.app.AlertDialog

val builder = AlertDialog.Builder(this)
builder.setTitle("Delete Account")
builder.setMessage("Are you sure you want to permanently delete your account? This action cannot be undone.")

// Positive Button
builder.setPositiveButton("Delete") { dialog, which ->
    // Logic to delete account
    performDeletion()
}

// Negative Button
builder.setNegativeButton("Cancel") { dialog, which ->
    // Dismiss the dialog automatically
    dialog.dismiss()
}

// Neutral Button (Optional)
builder.setNeutralButton("Remind Me Later") { dialog, which ->
    // Logic for later
}

// Prevent user from dismissing dialog by clicking outside of it
builder.setCancelable(false)

// Create and show the dialog
val dialog = builder.create()
dialog.show()

Custom Dialogs

You can also inflate your own XML layout into an AlertDialog to create fully custom popups (e.g., a mini login form).
kotlin
12345678910111213
val builder = AlertDialog.Builder(this)
val customView = layoutInflater.inflate(R.layout.dialog_custom, null)
builder.setView(customView)

val dialog = builder.create()
dialog.show()

// Access views inside the custom dialog
val submitButton = customView.findViewById<Button>(R.id.btnDialogSubmit)
submitButton.setOnClickListener {
    // Handle click
    dialog.dismiss()
}

4. Best Practices

  • Toasts: Use sparingly. They cannot be interacted with and might overlap with the keyboard.
  • Snackbars: The preferred method for brief, non-critical feedback in modern Android apps. Always attach them to the correct root view (e.g., a CoordinatorLayout allows the Snackbar to slide up and push floating action buttons out of the way).
  • Dialogs: Use only for critical interruptions. Do not use dialogs for simple information; interrupting the user's workflow is a poor UX pattern if overused.

5. Exercises

  1. 1. Create a screen with a "Save" button. When clicked, show a Toast saying "Saving...".
  1. 2. Create a "Delete File" button. When clicked, show an AlertDialog asking for confirmation. If the user clicks "Yes", show a Snackbar saying "File Deleted" with an "Undo" button.

6. Coding Challenge

The Note Taker App Flow Create a mock screen for a Note app.
  1. 1. When the user clicks the "Clear All Notes" button, show a critical AlertDialog warning them.
  1. 2. If they confirm, update a TextView to say "0 Notes".
  1. 3. Immediately show a Snackbar that says "Notes cleared" with an "UNDO" action.
  1. 4. If they click "UNDO" on the Snackbar, update the TextView back to "5 Notes" and show a Toast saying "Action undone".

7. Multiple Choice Questions (MCQs)

  1. 1. Which component is best suited for showing a message that requires a quick user action like "Undo"?
  • a) Toast
  • b) Snackbar
  • c) AlertDialog
  • d) Notification
  1. 2. How do you prevent an AlertDialog from closing when the user taps outside of it?
  • a) dialog.setCanceledOnTouchOutside(false)
  • b) dialog.setCancelable(false)
  • c) builder.setCancelable(false)
  • d) Both b and c
  1. 3. What is the first argument required by Toast.makeText()?
  • a) A View
  • b) A String
  • c) A Context (e.g., this in an Activity)
  • d) An Intent
  1. 4. True or False: You can add an image to a default AlertDialog using the Builder pattern.
  • a) True, using builder.setIcon()
  • b) False, you must use a Custom View.

8. Interview Questions

  1. 1. What is the difference between a Toast and a Snackbar?
*Answer*: A Toast is a simple, non-interactive system-level popup that appears for a fixed duration. A Snackbar is part of the UI (tied to a View), can contain a clickable action button, and can be swiped away by the user.
  1. 2. When should you use an AlertDialog instead of a Snackbar?
*Answer*: AlertDialogs should be used for critical, blocking decisions where the user *must* make a choice before continuing (e.g., confirming a destructive action, accepting terms). Snackbars are for lightweight feedback that doesn't block the user's flow.
  1. 3. How do you avoid memory leaks when showing Dialogs?
*Answer*: Always dismiss dialogs in the onDestroy() or onStop() method of your Activity/Fragment if they are currently showing, to prevent "Activity has leaked window" exceptions.

Finish this Chapter

Save your progress on your learning path and prepare for coding interview challenges.

Discussion

Join the discussion

Log in or create a free account to participate.

Sort: ·