Skip to content
Tutorials Center
My learning

Topics

Lesson 51 of 104 ยท Legacy Views

Menus, Toolbars, Drawers and Dialogs in the View System

Build options, context and popup menus, MaterialToolbar, NavigationView with DrawerLayout, AlertDialog, DialogFragment, bottom sheets, TabLayout and Snackbar with Views, plus Compose equivalents.

An app screen is more than its content. Users expect a top bar with actions, a side drawer for navigation, dialogs that ask for a decision, tabs and short messages at the bottom. In the View system each of these is a separate class with its own conventions. You will meet all of them in older apps, and most have a direct Compose counterpart.

This lesson shows the XML and Kotlin for the common ones. The Android code is read-only (it needs the SDK). The TryIts are plain Kotlin stand-ins that model the ideas: menu item dispatch, a dialog result callback and a snackbar queue. The Compose versions of the top bar and drawer are covered in Scaffold and App Bars.

A menu is a list of actions described in XML under res/menu/. The same file format serves three kinds of menus.

XML
<!-- read-only example: res/menu/main_menu.xml -->
<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" />

    <item
        android:id="@+id/action_share"
        android:title="@string/share"
        app:showAsAction="never" />

    <item
        android:id="@+id/action_settings"
        android:title="@string/settings"
        app:showAsAction="never" />
</menu>

showAsAction decides whether an item is shown as an icon in the toolbar (ifRoom, always) or in the overflow menu (never, the three dots).

Options menu

The options menu belongs to the screen's toolbar. In an Activity you override onCreateOptionsMenu and onOptionsItemSelected. In a Fragment the modern way is to register a MenuProvider with requireActivity().addMenuProvider(...), because setHasOptionsMenu is deprecated:

Kotlin
// read-only example: inside a Fragment
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
    requireActivity().addMenuProvider(object : MenuProvider {
        override fun onCreateMenu(menu: Menu, inflater: MenuInflater) {
            inflater.inflate(R.menu.main_menu, menu)
        }

        override fun onMenuItemSelected(item: MenuItem): Boolean = when (item.itemId) {
            R.id.action_search -> { viewModel.openSearch(); true }
            R.id.action_share -> { shareCurrentItem(); true }
            else -> false
        }
    }, viewLifecycleOwner, Lifecycle.State.RESUMED)
}

Returning true means "I handled it"; false lets other handlers run. Passing viewLifecycleOwner removes the menu when the fragment's view goes away, so you do not leak it.

Context menu and contextual action mode

A context menu appears on long press of a view registered with registerForContextMenu(view), and is built in onCreateContextMenu. On phones, a contextual action mode (startActionMode) is usually better: it replaces the toolbar with actions that apply to the selected items, which is the pattern for multi-select in a list.

PopupMenu anchors a menu to any view, for example a "more" button on a list row:

Kotlin
// read-only example
binding.moreButton.setOnClickListener { anchor ->
    PopupMenu(anchor.context, anchor).apply {
        menuInflater.inflate(R.menu.row_menu, menu)
        setOnMenuItemClickListener { item ->
            when (item.itemId) {
                R.id.delete -> { viewModel.delete(rowId); true }
                else -> false
            }
        }
        show()
    }
}

In Compose, DropdownMenu plus DropdownMenuItem covers popup menus (state controls expanded), and the options menu is just IconButtons in the actions slot of a TopAppBar.

The stand-in below models the dispatch: a menu is a list of items, the screen handles some ids, and a false result falls through to the next handler (the activity, for example).

Kotlin Menu item dispatch (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

Toolbar and MaterialToolbar

A Toolbar is a view you place anywhere in a layout. MaterialToolbar is the Material 3 version with a title, navigation icon and menu. Put it in an AppBarLayout / CoordinatorLayout to get collapsing and scrolling behavior, or use MaterialToolbar directly:

XML
<!-- read-only example -->
<com.google.android.material.appbar.MaterialToolbar
    android:id="@+id/toolbar"
    android:layout_width="match_parent"
    android:layout_height="?attr/actionBarSize"
    app:title="@string/app_name"
    app:navigationIcon="@drawable/ic_menu"
    app:menu="@menu/main_menu" />
Kotlin
// read-only example
binding.toolbar.setNavigationOnClickListener { binding.drawerLayout.open() }
binding.toolbar.setOnMenuItemClickListener { item -> handle(item) }

Notice that app:menu inflates the menu straight into the toolbar. With an AppCompatActivity that uses a NoActionBar theme you can instead call setSupportActionBar(binding.toolbar) and use the options-menu callbacks. Do not mix both styles on one screen.

A navigation drawer slides in from the edge. DrawerLayout is the root with exactly two children: the main content first, and the NavigationView (the drawer) last, with layout_gravity="start".

XML
<!-- read-only example -->
<androidx.drawerlayout.widget.DrawerLayout
    android:id="@+id/drawerLayout"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <androidx.fragment.app.FragmentContainerView
        android:id="@+id/content"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

    <com.google.android.material.navigation.NavigationView
        android:id="@+id/navView"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        app:headerLayout="@layout/drawer_header"
        app:menu="@menu/drawer_menu" />
</androidx.drawerlayout.widget.DrawerLayout>
Kotlin
// read-only example
binding.navView.setNavigationItemSelectedListener { item ->
    when (item.itemId) {
        R.id.nav_home -> showHome()
        R.id.nav_settings -> showSettings()
    }
    binding.drawerLayout.closeDrawers()
    true
}

With the Navigation component you connect the menu ids to destinations (navView.setupWithNavController(navController)), and a menu item whose id equals a destination id navigates automatically. Material 3 guidance prefers a bottom navigation bar for three to five top-level places on phones and a navigation rail or a permanent drawer on large screens (see Adaptive Layouts). In Compose, use ModalNavigationDrawer with ModalDrawerSheet and NavigationDrawerItem.

AlertDialog

AlertDialog asks for a decision. Use MaterialAlertDialogBuilder so the dialog follows your Material theme:

Kotlin
// read-only example
MaterialAlertDialogBuilder(requireContext())
    .setTitle(R.string.delete_title)
    .setMessage(R.string.delete_message)
    .setNegativeButton(R.string.cancel, null)
    .setPositiveButton(R.string.delete) { _, _ -> viewModel.delete(itemId) }
    .show()

You can also use setItems, setSingleChoiceItems, setMultiChoiceItems, or setView for a custom layout. Keep dialogs short, name the action on the button (Delete, not OK), and ask only for destructive or important choices.

DialogFragment

A dialog created directly with show() is destroyed on rotation, because it belongs to the activity's window and is not restored. A DialogFragment is a fragment that shows a dialog, so the system recreates it after configuration changes. This is why serious dialogs are DialogFragments.

Kotlin
// read-only example
class ConfirmDeleteDialog : DialogFragment() {
    override fun onCreateDialog(savedInstanceState: Bundle?): Dialog =
        MaterialAlertDialogBuilder(requireContext())
            .setTitle(R.string.delete_title)
            .setPositiveButton(R.string.delete) { _, _ ->
                setFragmentResult(REQUEST_KEY, bundleOf("confirmed" to true))
            }
            .setNegativeButton(R.string.cancel, null)
            .create()

    companion object { const val REQUEST_KEY = "confirm_delete" }
}

// in the host fragment
childFragmentManager.setFragmentResultListener(ConfirmDeleteDialog.REQUEST_KEY, viewLifecycleOwner) { _, bundle ->
    if (bundle.getBoolean("confirmed")) viewModel.delete(itemId)
}
ConfirmDeleteDialog().show(childFragmentManager, "confirm_delete")

The Fragment Result API (setFragmentResult and setFragmentResultListener) returns the answer without the dialog holding a reference to its host. Dialog fragments are described further in Fragments. In Compose, AlertDialog(onDismissRequest = ..., confirmButton = ...) is shown by an if (state.showDialog), so the dialog state survives rotation in the ViewModel.

The stand-in below models the result flow: the dialog reports a result under a key, the host registers a listener, and a "rotation" shows why holding the state outside the dialog matters.

Kotlin Fragment result flow for a dialog (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

Bottom sheets

A bottom sheet slides up from the bottom. A modal sheet blocks the screen behind it, like a dialog; a standard sheet is part of the layout and stays beside the content.

  • BottomSheetDialogFragment (Material Components) is the modal version: subclass it, inflate your layout in onCreateView and call show(childFragmentManager, tag).
  • BottomSheetBehavior attached to a view in a CoordinatorLayout (app:layout_behavior="com.google.android.material.bottomsheet.BottomSheetBehavior") creates a standard sheet, with states STATE_COLLAPSED, STATE_EXPANDED, STATE_HIDDEN.
Kotlin
// read-only example
class FilterSheet : BottomSheetDialogFragment() {
    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, state: Bundle?): View =
        SheetFilterBinding.inflate(inflater, container, false).root
}
// FilterSheet().show(childFragmentManager, "filters")

In Compose, use ModalBottomSheet with a rememberModalBottomSheetState() or BottomSheetScaffold for a standard sheet.

TabLayout

TabLayout shows a row of tabs. It is paired with a ViewPager2 for swipeable pages, and a TabLayoutMediator links them and sets the tab labels:

Kotlin
// read-only example
binding.pager.adapter = PagerAdapter(this)           // FragmentStateAdapter
TabLayoutMediator(binding.tabs, binding.pager) { tab, position ->
    tab.text = titles[position]
}.attach()

You can also use a TabLayout alone, with addOnTabSelectedListener to swap content. Compose has TabRow / ScrollableTabRow with Tab, and HorizontalPager for swiping; see Tabs and Pager.

Snackbar and Toast

Both show a short message without blocking the user.

  • Toast is a plain floating message with no interaction. Since Android 11 custom toasts from the background are restricted, and it cannot be styled or have an action, so use it sparingly.
  • Snackbar appears at the bottom, can have an action ("Undo") and goes away by itself or when swiped. It needs a view to attach to, and finds a CoordinatorLayout parent so it can move other views out of the way.
Kotlin
// read-only example
Snackbar.make(binding.root, R.string.item_deleted, Snackbar.LENGTH_LONG)
    .setAction(R.string.undo) { viewModel.undoDelete() }
    .show()

Compose uses a SnackbarHostState in a Scaffold, calling snackbarHostState.showSnackbar(message, actionLabel), which is a suspend function that returns whether the action was clicked, as you saw in Scaffold and App Bars. The stand-in below models a snackbar queue that shows one message at a time and returns the outcome.

Kotlin A snackbar queue with Undo (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

Which component for which job?

Pick the right surface

Menu or toolbar Actions for this screen
Drawer, tabs Moving between places
Dialog A decision that blocks
Snackbar A short message with Undo

Choose the lightest component that does the job.

1 / 2

Common mistakes

  • Showing an AlertDialog straight from an activity or fragment for important flows, which vanishes on rotation. Use DialogFragment, or keep the dialog state in a ViewModel in Compose.
  • Leaking a menu with setHasOptionsMenu (deprecated). Use MenuProvider tied to viewLifecycleOwner.
  • Two toolbars. Do not set a support action bar and also put a MaterialToolbar in each fragment unless you manage both.
  • Forgetting to close the drawer after a navigation click.
  • Using Toast for errors the user must act on. A snackbar with an action, or a dialog, is better.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does returning true from onMenuItemSelected mean?

    Returning true consumes the event. Returning false lets other handlers (such as the activity) try.
  2. 2. Why use a DialogFragment instead of showing an AlertDialog directly from an activity?

    A dialog shown directly is lost when the activity is recreated. A DialogFragment is part of the fragment back stack and is restored.
  3. 3. In a DrawerLayout, which child must come first?

    The main content must be the first child; the drawer (with layout_gravity start or end) comes after it.
  4. 4. What can a Snackbar do that a Toast cannot?

    A Snackbar can have an action button and is attached to the layout, so users can react to it. A Toast is non-interactive.
  5. 5. Which Compose component replaces a modal bottom sheet from Material Components?

    ModalBottomSheet (with a sheet state) is the Material 3 Compose counterpart of BottomSheetDialogFragment.

Summary

  • Menus are XML files under res/menu/: options menus use a MenuProvider (or the activity callbacks), context menus appear on long press, popup menus attach to any view.
  • MaterialToolbar is the top bar; DrawerLayout with NavigationView is the side drawer, and Navigation component can drive it.
  • MaterialAlertDialogBuilder builds dialogs; wrap important ones in a DialogFragment and return results with the Fragment Result API.
  • Bottom sheets use BottomSheetDialogFragment (modal) or BottomSheetBehavior (standard); TabLayout pairs with ViewPager2.
  • Use a Snackbar for short messages with Undo, and avoid Toast for anything actionable.
  • Compose counterparts: TopAppBar, DropdownMenu, ModalNavigationDrawer, AlertDialog, ModalBottomSheet, TabRow, SnackbarHost.

Next: Navigation Compose Basics