Dialogs & Menus

User feedback and actions with dialogs, toasts, snackbars, and menus

AlertDialog Toast Snackbar Menus

Table of Contents

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.

ComponentTypeBest For
AlertDialogModal dialogConfirmations, warnings, simple choices
Custom DialogModal dialogForms, ratings, rich custom UI
ToastTransient messageQuick non-interactive feedback
SnackbarBottom bar messageFeedback with optional action (Undo)
Options MenuApp bar / toolbarGlobal app actions (Search, Settings)
Context MenuLong-press menuActions on a specific item (legacy)
Popup MenuDropdown anchored to viewOverflow or item-specific actions

1AlertDialog

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 confirmationAlertDialog.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 themeval 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 interestsval 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()

2Custom 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 approachclass 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 dialogAddContactDialogFragment().show(supportFragmentManager, "AddContact")

3Toast

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 ToastToast.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 layoutval 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

FeatureToastSnackbar
Action buttonNoYes (Undo, Retry)
Swipe to dismissNoYes
Material DesignBasicFull Material styling
Anchor to viewNoYes (above FAB, etc.)

4Snackbar

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 Snackbarval rootView = findViewById<View>(R.id.main) Snackbar.make(rootView, "Profile updated", Snackbar.LENGTH_SHORT).show()

Snackbar with action (Undo)

Kotlin — Undo deletevar 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 FABSnackbar.make(findViewById(R.id.coordinator), "Item saved", Snackbar.LENGTH_SHORT) .setAnchorView(R.id.fabAdd) .show()

Custom Snackbar styling

Kotlin — Colored Snackbarval 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()

5Options Menu

The Options Menu appears in the app bar (toolbar). It holds global actions like Search, Settings, Share, and overflow items (three-dot menu).

Menu XML resource

XML — res/menu/main_menu.xml<?xml version="1.0" encoding="utf-8"?> <menu xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto"> <item android:id="@+id/action_search" android:icon="@drawable/ic_search" android:title="@string/search" app:showAsAction="ifRoom|collapseActionView" app:actionViewClass="androidx.appcompat.widget.SearchView" /> <item android:id="@+id/action_share" android:icon="@drawable/ic_share" android:title="@string/share" app:showAsAction="ifRoom" /> <item android:id="@+id/action_settings" android:title="@string/settings" app:showAsAction="never" /> <item android:id="@+id/action_about" android:title="@string/about" app:showAsAction="never" /> </menu>

Inflate and handle in Activity

Kotlin — Options menu handlingclass MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) setSupportActionBar(findViewById(R.id.toolbar)) } override fun onCreateOptionsMenu(menu: Menu): Boolean { menuInflater.inflate(R.menu.main_menu, menu) return true } override fun onOptionsItemSelected(item: MenuItem): Boolean { return when (item.itemId) { R.id.action_search -> { Toast.makeText(this, "Search tapped", Toast.LENGTH_SHORT).show() true } R.id.action_share -> { shareApp() true } R.id.action_settings -> { startActivity(Intent(this, SettingsActivity::class.java)) true } R.id.action_about -> { showAboutDialog() true } else -> super.onOptionsItemSelected(item) } } }

showAsAction values

ValueBehavior
alwaysAlways show as icon in app bar
ifRoomShow icon if space allows, else overflow
neverAlways in overflow (three-dot) menu
withTextShow icon with title text

6Context Menu

A Context Menu appears on long-press of a view — typically for item-specific actions like Edit, Delete, or Share on a list row. Note: Google recommends PopupMenu or action modes for new apps.

Context menu XML

XML — res/menu/context_menu.xml<?xml version="1.0" encoding="utf-8"?> <menu xmlns:android="http://schemas.android.com/apk/res/android"> <item android:id="@+id/context_edit" android:title="@string/edit" android:icon="@drawable/ic_edit" /> <item android:id="@+id/context_delete" android:title="@string/delete" android:icon="@drawable/ic_delete" /> <item android:id="@+id/context_share" android:title="@string/share" android:icon="@drawable/ic_share" /> </menu>

Register and handle context menu

Kotlin — Context menu on ListView itemclass MainActivity : AppCompatActivity() { private var selectedPosition = -1 override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) val listView = findViewById<ListView>(R.id.listView) registerForContextMenu(listView) listView.setOnItemLongClickListener { _, _, position, _ -> selectedPosition = position false // false = still show context menu } } override fun onCreateContextMenu( menu: ContextMenu, v: View, menuInfo: ContextMenu.ContextMenuInfo? ) { super.onCreateContextMenu(menu, v, menuInfo) menuInflater.inflate(R.menu.context_menu, menu) if (menuInfo is AdapterView.AdapterContextMenuInfo) { selectedPosition = menuInfo.position menu.setHeaderTitle(contacts[selectedPosition].name) } } override fun onContextItemSelected(item: MenuItem): Boolean { return when (item.itemId) { R.id.context_edit -> { editContact(selectedPosition) true } R.id.context_delete -> { deleteContact(selectedPosition) true } R.id.context_share -> { shareContact(selectedPosition) true } else -> super.onContextItemSelected(item) } } }

Modern alternative: For RecyclerView items, use PopupMenu on long-press or a three-dot icon — more flexible and consistent with Material Design.

8Hands-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?

ALong scrolling lists
BSimple confirmations and choices
CBackground sync
DDatabase queries
Explanation: AlertDialog shows title, message, and buttons for user decisions.
2

Toast displays messages?

AOnly in notification shade
BUntil user dismisses always
CBriefly without blocking UI
DOnly on lock screen
Explanation: Toast is a transient popup — use Snackbar for Material apps with actions.
3

Snackbar can include?

AGPS coordinates
BOnly images
CVideo playback
DAn action button like Undo
Explanation: Snackbar supports action callbacks and appears at bottom with coordinator behavior.
4

Options Menu appears in?

AApp bar / toolbar overflow
BNotification channel
CManifest only
DGradle file
Explanation: Inflated via onCreateOptionsMenu for toolbar actions.
5

Context Menu triggered by?

ADouble tap only
BLong-press on a view
CApp install
DGradle sync
Explanation: registerForContextMenu associates long-press menu with a view.
6

PopupMenu shows?

ASystem settings
BFull screen Activity
CDropdown anchored to a view
DLogcat output
Explanation: PopupMenu displays menu items near a button or list row.
7

DialogFragment advantage?

ANo manifest needed
BFaster than SQLite
CReplaces Services
DSurvives rotation with proper lifecycle
Explanation: DialogFragment is lifecycle-aware vs raw Dialog.
8

MaterialAlertDialogBuilder provides?

AMaterial-styled dialogs
BBluetooth pairing
CRoom migrations
DCamera preview
Explanation: Use MaterialAlertDialogBuilder for themed Material dialogs.
9

onOptionsItemSelected returns true when?

AMenu should reopen
BItem was handled
CActivity finishes
DAlways false
Explanation: Return true to indicate the menu click was consumed.
10

Custom dialog layout inflated with?

AIntent filter
BSQLiteOpenHelper
CLayoutInflater into AlertDialog setView
DADB only
Explanation: Inflate custom XML and pass root view to AlertDialog.Builder.setView().

10 Advanced Dialogs & Menus MCQs

11

Snackbar requires?

AForeground service
BCoordinatorLayout or compatible anchor for proper behavior
CRoom database
DCamera permission always
Explanation: CoordinatorLayout enables swipe-dismiss and FAB offset behavior.
12

BottomSheetDialogFragment used for?

AGPS tracking
BSQLite queries
CModal bottom sheets with custom layout
DAPK signing
Explanation: Bottom sheets are Material modal dialogs sliding from bottom.
13

PopupMenu gravity affects?

ADex version
BDatabase schema
CNotification priority
DWhere menu appears relative to anchor
Explanation: Gravity.TOP, END, etc. position the popup near the anchor view.
14

Dialog setCancelable(false) means?

AUser cannot dismiss by back/outside tap
BAuto dismiss in 1 sec
CIllegal on Android 14
DRequires permission
Explanation: Force explicit button choice for critical dialogs.
15

onPrepareOptionsMenu called when?

AOnly onCreate once ever
BBefore menu shown — update visibility
CApp uninstall
DService bind
Explanation: Use to show/hide menu items dynamically before display.
16

Toast vs Snackbar for errors?

ANeither allowed
BToast always better
CPrefer Snackbar — can add Retry action
DUse Notification only
Explanation: Snackbar integrates with Material design and supports actions.
17

Context menu on RecyclerView item?

ARequires root
BImpossible
CManifest intent only
DRegister 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?

AFinding fragment later via FragmentManager
BEncryption
CNetwork URL
DProGuard keep
Explanation: Tag string identifies dialog in back stack and findFragmentByTag.
19

ActionMode provides?

ABackground download
BContextual action bar for multi-select
CRoom DAO
DSensor fusion
Explanation: ActionMode shows contextual toolbar when items selected (CAB pattern).
20

MenuInflater role?

AStarts Services
BInflates layouts only
CInflates menu XML into Menu object
DParses JSON
Explanation: menuInflater.inflate(R.menu.main, menu) in onCreateOptionsMenu.
Click an option to select, then check answers.

Dialogs & Menus Interview Q&A

15 topic-focused questions for interviews and revision.

1When 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.
2How to show a confirmation before delete?easy
Answer: AlertDialog.Builder with setPositiveButton for confirm and setNegativeButton for cancel; perform delete in positive callback.
3Difference between Toast and Snackbar.easy
Answer: Toast is system overlay, no actions, deprecated patterns; Snackbar is Material, supports actions, anchors to CoordinatorLayout.
4Steps to add Options Menu.easy
Answer: Create res/menu XML, override onCreateOptionsMenu to inflate, handle clicks in onOptionsItemSelected.
5What is a PopupMenu?easy
Answer: Dropdown menu anchored to a view — common for overflow actions on list rows.
6Why use DialogFragment over Dialog?medium
Answer: Survives configuration changes when properly managed, integrates with Fragment lifecycle and back stack.
7Implement Snackbar with Undo action.medium
Answer: Snackbar.make(view, msg, LENGTH_LONG).setAction("Undo") { revert delete }.show()
8Context menu vs PopupMenu — modern preference?medium
Answer: PopupMenu is preferred for list row actions; context menu is legacy but still works with registerForContextMenu.
9How 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.
10MaterialAlertDialogBuilder example use case.easy
Answer: Themed delete confirmation matching app Material color scheme and typography.
11Prevent dialog dismiss on outside touch.medium
Answer: setCancelable(false) and setCanceledOnTouchOutside(false) on dialog window.
12Show different menu items for admin vs user.medium
Answer: Override onPrepareOptionsMenu; setVisible on MenuItem based on user role from ViewModel.
13BottomSheetDialogFragment vs AlertDialog.medium
Answer: Bottom sheet for filters, pickers, or mobile-first forms; AlertDialog for short confirmations.
14Accessibility for dialogs.hard
Answer: Set title, message read by TalkBack; ensure focus moves to dialog; actionable buttons have clear labels.
15Common dialog memory leak.hard
Answer: Holding Activity reference in non-static Dialog callback — use weak reference or DialogFragment with viewLifecycleOwner.