Dialogs & Menus
User feedback and actions with dialogs, toasts, snackbars, and menus
AlertDialog
Toast
Snackbar
Menus
Dialogs & Menus Overview
Android provides several ways to communicate with users and offer actions: blocking dialogs for decisions, lightweight toasts for brief feedback, snackbars with undo actions, and menus for structured choices.
Component Type Best For
AlertDialog Modal dialog Confirmations, warnings, simple choices
Custom Dialog Modal dialog Forms, ratings, rich custom UI
Toast Transient message Quick non-interactive feedback
Snackbar Bottom bar message Feedback with optional action (Undo)
Options Menu App bar / toolbar Global app actions (Search, Settings)
Context Menu Long-press menu Actions on a specific item (legacy)
Popup Menu Dropdown anchored to view Overflow or item-specific actions
1 AlertDialog
AlertDialog is a modal dialog that interrupts the user for a decision — confirm delete, pick an option, or show a message with action buttons.
Basic confirmation dialog
Kotlin — Delete confirmation AlertDialog.Builder(this)
.setTitle("Delete Item")
.setMessage("Are you sure you want to delete this contact?")
.setPositiveButton("Delete") { dialog, _ ->
deleteContact()
dialog.dismiss()
}
.setNegativeButton("Cancel") { dialog, _ ->
dialog.dismiss()
}
.setIcon(R.drawable.ic_warning)
.setCancelable(false)
.show()
Material AlertDialog (recommended)
Kotlin — MaterialAlertDialogBuilder // dependencies { implementation("com.google.android.material:material:1.11.0") }
MaterialAlertDialogBuilder(this)
.setTitle(R.string.logout_title)
.setMessage(R.string.logout_message)
.setPositiveButton(R.string.yes) { _, _ -> logout() }
.setNegativeButton(R.string.no, null)
.show()
Single-choice list dialog
Kotlin — Pick theme val themes = arrayOf("Light", "Dark", "System Default")
var selectedIndex = 0
AlertDialog.Builder(this)
.setTitle("Choose Theme")
.setSingleChoiceItems(themes, selectedIndex) { _, which ->
selectedIndex = which
}
.setPositiveButton("Apply") { _, _ ->
applyTheme(themes[selectedIndex])
}
.setNegativeButton("Cancel", null)
.show()
Multi-choice dialog
Kotlin — Select interests val items = arrayOf("Kotlin", "Java", "Compose", "Firebase")
val checked = booleanArrayOf(false, false, false, false)
AlertDialog.Builder(this)
.setTitle("Select Interests")
.setMultiChoiceItems(items, checked) { _, index, isChecked ->
checked[index] = isChecked
}
.setPositiveButton("Save") { _, _ ->
val selected = items.filterIndexed { i, _ -> checked[i] }
saveInterests(selected)
}
.show()
2 Custom Dialog
A custom dialog uses your own XML layout for richer UI — login forms, rating stars, image previews, or multi-field inputs.
Custom layout XML
XML — dialog_add_contact.xml <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:padding="24dp">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/add_contact"
android:textSize="20sp"
android:textStyle="bold"
android:layout_marginBottom="16dp" />
<EditText
android:id="@+id/etDialogName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="@string/name_hint"
android:inputType="textPersonName"
android:layout_marginBottom="12dp" />
<EditText
android:id="@+id/etDialogPhone"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="@string/phone_hint"
android:inputType="phone"
android:layout_marginBottom="20dp" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:gravity="end">
<Button
android:id="@+id/btnCancel"
style="@style/Widget.Material3.Button.TextButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/cancel" />
<Button
android:id="@+id/btnSave"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/save" />
</LinearLayout>
</LinearLayout>
Show custom dialog
Kotlin — Custom DialogFragment approach class AddContactDialogFragment : DialogFragment() {
interface Listener {
fun onContactSaved(name: String, phone: String)
}
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
val view = layoutInflater.inflate(R.layout.dialog_add_contact, null)
val etName = view.findViewById<EditText>(R.id.etDialogName)
val etPhone = view.findViewById<EditText>(R.id.etDialogPhone)
val dialog = AlertDialog.Builder(requireContext())
.setView(view)
.create()
view.findViewById<Button>(R.id.btnCancel).setOnClickListener { dialog.dismiss() }
view.findViewById<Button>(R.id.btnSave).setOnClickListener {
val name = etName.text.toString().trim()
val phone = etPhone.text.toString().trim()
if (name.isNotEmpty()) {
(activity as? Listener)?.onContactSaved(name, phone)
dialog.dismiss()
} else {
etName.error = "Name required"
}
}
return dialog
}
}
Show from Activity
Kotlin — Display dialog AddContactDialogFragment().show(supportFragmentManager, "AddContact")
3 Toast
Toast shows a short, non-blocking message at the bottom of the screen. It auto-dismisses and cannot contain interactive buttons — use Snackbar when you need an action.
Basic Toast
Kotlin — Simple Toast Toast.makeText(this, "Saved successfully!", Toast.LENGTH_SHORT).show()
// Longer duration (~3.5 seconds)
Toast.makeText(this, "Upload complete", Toast.LENGTH_LONG).show()
Custom Toast with layout
Kotlin — Custom Toast layout val inflater = layoutInflater
val layout = inflater.inflate(R.layout.custom_toast, findViewById(R.id.toast_container))
layout.findViewById<TextView>(R.id.tvToastMessage).text = "Item added to cart"
with(Toast(applicationContext)) {
duration = Toast.LENGTH_SHORT
view = layout
setGravity(Gravity.BOTTOM or Gravity.CENTER_HORIZONTAL, 0, 100)
show()
}
Best practice: Avoid overusing Toast — users cannot interact with it and it disappears quickly. Prefer Snackbar for actionable feedback. Never use Toast for errors that need user attention; use a dialog instead.
Toast vs Snackbar
Feature Toast Snackbar
Action button No Yes (Undo, Retry)
Swipe to dismiss No Yes
Material Design Basic Full Material styling
Anchor to view No Yes (above FAB, etc.)
4 Snackbar
Snackbar is Material Design's bottom message bar. It supports an action button, swipe-to-dismiss, and can anchor above FABs or BottomNavigationView.
Basic Snackbar
Kotlin — Simple Snackbar val rootView = findViewById<View>(R.id.main)
Snackbar.make(rootView, "Profile updated", Snackbar.LENGTH_SHORT).show()
Snackbar with action (Undo)
Kotlin — Undo delete var deletedContact: Contact? = null
var deletedPosition = -1
fun deleteContact(position: Int) {
deletedContact = contacts[position]
deletedPosition = position
contacts.removeAt(position)
adapter.notifyItemRemoved(position)
Snackbar.make(recyclerView, "Contact deleted", Snackbar.LENGTH_LONG)
.setAction("Undo") {
deletedContact?.let { contact ->
contacts.add(deletedPosition, contact)
adapter.notifyItemInserted(deletedPosition)
}
}
.show()
}
Anchor above FAB
Kotlin — Snackbar above FAB Snackbar.make(findViewById(R.id.coordinator), "Item saved", Snackbar.LENGTH_SHORT)
.setAnchorView(R.id.fabAdd)
.show()
Custom Snackbar styling
Kotlin — Colored Snackbar val snackbar = Snackbar.make(rootView, "Error saving data", Snackbar.LENGTH_INDEFINITE)
.setAction("Retry") { retrySave() }
.setActionTextColor(ContextCompat.getColor(this, R.color.snackbar_action))
snackbar.view.setBackgroundColor(ContextCompat.getColor(this, R.color.error_red))
snackbar.show()
8 Hands-On Exercises
1
Show an AlertDialog when the user taps Delete — confirm before removing a list item.
2
Build a custom dialog with name and phone EditText fields. Return the data to the Activity via a callback interface.
3
Replace all Toast messages with Snackbar . Add an "Undo" action when deleting a RecyclerView item.
4
Add an Options Menu to the toolbar with Search, Share, and Settings items. Handle each in onOptionsItemSelected.
5
Implement a Context Menu on long-press of a ListView item with Edit and Delete options.
6
Add a three-dot icon to each RecyclerView row. Show a PopupMenu with View, Edit, and Delete actions.
7
Bonus: Create a single-choice AlertDialog for sorting (Name A–Z, Date, Priority) and reorder the list accordingly.
Dialogs & Menus MCQ Practice
10 Basic MCQs
10 Advanced MCQs
10 Basic Dialogs & Menus MCQs
1
AlertDialog is best for?
A Long scrolling lists
B Simple confirmations and choices
C Background sync
D Database queries
Explanation: AlertDialog shows title, message, and buttons for user decisions.
2
Toast displays messages?
A Only in notification shade
B Until user dismisses always
C Briefly without blocking UI
D Only on lock screen
Explanation: Toast is a transient popup — use Snackbar for Material apps with actions.
3
Snackbar can include?
A GPS coordinates
B Only images
C Video playback
D An action button like Undo
Explanation: Snackbar supports action callbacks and appears at bottom with coordinator behavior.
4
Options Menu appears in?
A App bar / toolbar overflow
B Notification channel
C Manifest only
D Gradle file
Explanation: Inflated via onCreateOptionsMenu for toolbar actions.
5
Context Menu triggered by?
A Double tap only
B Long-press on a view
C App install
D Gradle sync
Explanation: registerForContextMenu associates long-press menu with a view.
6
PopupMenu shows?
A System settings
B Full screen Activity
C Dropdown anchored to a view
D Logcat output
Explanation: PopupMenu displays menu items near a button or list row.
7
DialogFragment advantage?
A No manifest needed
B Faster than SQLite
C Replaces Services
D Survives rotation with proper lifecycle
Explanation: DialogFragment is lifecycle-aware vs raw Dialog.
8
MaterialAlertDialogBuilder provides?
A Material-styled dialogs
B Bluetooth pairing
C Room migrations
D Camera preview
Explanation: Use MaterialAlertDialogBuilder for themed Material dialogs.
9
onOptionsItemSelected returns true when?
A Menu should reopen
B Item was handled
C Activity finishes
D Always false
Explanation: Return true to indicate the menu click was consumed.
10
Custom dialog layout inflated with?
A Intent filter
B SQLiteOpenHelper
C LayoutInflater into AlertDialog setView
D ADB only
Explanation: Inflate custom XML and pass root view to AlertDialog.Builder.setView().
10 Advanced Dialogs & Menus MCQs
11
Snackbar requires?
A Foreground service
B CoordinatorLayout or compatible anchor for proper behavior
C Room database
D Camera permission always
Explanation: CoordinatorLayout enables swipe-dismiss and FAB offset behavior.
12
BottomSheetDialogFragment used for?
A GPS tracking
B SQLite queries
C Modal bottom sheets with custom layout
D APK signing
Explanation: Bottom sheets are Material modal dialogs sliding from bottom.
13
PopupMenu gravity affects?
A Dex version
B Database schema
C Notification priority
D Where menu appears relative to anchor
Explanation: Gravity.TOP, END, etc. position the popup near the anchor view.
14
Dialog setCancelable(false) means?
A User cannot dismiss by back/outside tap
B Auto dismiss in 1 sec
C Illegal on Android 14
D Requires permission
Explanation: Force explicit button choice for critical dialogs.
15
onPrepareOptionsMenu called when?
A Only onCreate once ever
B Before menu shown — update visibility
C App uninstall
D Service bind
Explanation: Use to show/hide menu items dynamically before display.
16
Toast vs Snackbar for errors?
A Neither allowed
B Toast always better
C Prefer Snackbar — can add Retry action
D Use Notification only
Explanation: Snackbar integrates with Material design and supports actions.
17
Context menu on RecyclerView item?
A Requires root
B Impossible
C Manifest intent only
D Register view in onBindViewHolder or use PopupMenu
Explanation: Modern apps often use PopupMenu on row action icon instead of legacy context menu.
18
DialogFragment show() tag used for?
A Finding fragment later via FragmentManager
B Encryption
C Network URL
D ProGuard keep
Explanation: Tag string identifies dialog in back stack and findFragmentByTag.
19
ActionMode provides?
A Background download
B Contextual action bar for multi-select
C Room DAO
D Sensor fusion
Explanation: ActionMode shows contextual toolbar when items selected (CAB pattern).
20
MenuInflater role?
A Starts Services
B Inflates layouts only
C Inflates menu XML into Menu object
D Parses JSON
Explanation: menuInflater.inflate(R.menu.main, menu) in onCreateOptionsMenu.
Check All Answers
Click an option to select, then check answers.
Dialogs & Menus Interview Q&A
15 topic-focused questions for interviews and revision.
1 When to use AlertDialog vs custom dialog?easy
Answer: AlertDialog for simple text/buttons; custom dialog when you need complex forms, images, or custom styling in a layout XML.
2 How to show a confirmation before delete?easy
Answer: AlertDialog.Builder with setPositiveButton for confirm and setNegativeButton for cancel; perform delete in positive callback.
3 Difference between Toast and Snackbar.easy
Answer: Toast is system overlay, no actions, deprecated patterns; Snackbar is Material, supports actions, anchors to CoordinatorLayout.
4 Steps to add Options Menu.easy
Answer: Create res/menu XML, override onCreateOptionsMenu to inflate, handle clicks in onOptionsItemSelected.
5 What is a PopupMenu?easy
Answer: Dropdown menu anchored to a view — common for overflow actions on list rows.
6 Why use DialogFragment over Dialog?medium
Answer: Survives configuration changes when properly managed, integrates with Fragment lifecycle and back stack.
7 Implement Snackbar with Undo action.medium
Answer: Snackbar.make(view, msg, LENGTH_LONG).setAction("Undo") { revert delete }.show()
8 Context menu vs PopupMenu — modern preference?medium
Answer: PopupMenu is preferred for list row actions; context menu is legacy but still works with registerForContextMenu.
9 How to pass data from custom dialog to Activity?medium
Answer: Define callback interface, set listener on dialog fragment, invoke on button click with entered values.
10 MaterialAlertDialogBuilder example use case.easy
Answer: Themed delete confirmation matching app Material color scheme and typography.
11 Prevent dialog dismiss on outside touch.medium
Answer: setCancelable(false) and setCanceledOnTouchOutside(false) on dialog window.
12 Show different menu items for admin vs user.medium
Answer: Override onPrepareOptionsMenu; setVisible on MenuItem based on user role from ViewModel.
13 BottomSheetDialogFragment vs AlertDialog.medium
Answer: Bottom sheet for filters, pickers, or mobile-first forms; AlertDialog for short confirmations.
14 Accessibility for dialogs.hard
Answer: Set title, message read by TalkBack; ensure focus moves to dialog; actionable buttons have clear labels.
15 Common dialog memory leak.hard
Answer: Holding Activity reference in non-static Dialog callback — use weak reference or DialogFragment with viewLifecycleOwner.