ProAndroidDev

The latest posts from Android Professionals and Google Developer Experts.

Follow publication

MenuProvider API— Android

In this article, we will learn how to use the MenuProvider API to add the Options menu to the toolbar.

Major components

  • MenuHost
  • MenuProvider
  • LifecycleOwner
  • LifecycleOwner.State

setHasOptionsMenu() , onCreateOptionsMenu(), onOptionsItemSelected() — Deprecated 🛑

https://developer.android.com/reference/androidx/fragment/app/Fragment.html#setHasOptionsMenu(boolean)

MenuProvider

It's an interface that contains four methods

  1. onCreateMenu: Here we inflate the menu for the Options
  2. onMenuItemSelected: Here we handle what happens when the user clicks on one of the items in the Options menu
  3. onPrepareMenu: For customizing menu items, you need to put the code here.
    You can, for example, change the visibility of a view or customize the layout of menu items.
  4. onMenuClosed: Its called when the menu is closed

MenuHost

  • Interface implemented by ComponentActivity, AppCompactActivity which provides us with various methods to control the Menu added using the MenuProvider

It has the following threemethods:

https://gist.github.com/navczydev/910ca2b85d3bd078ac0f8c1bebf9213e

Adding menu from Activity

addMenuProvider(object : MenuProvider {
override fun onCreateMenu(menu: Menu, menuInflater: MenuInflater) {
menuInflater.inflate(R.menu.main_menu, menu)
}
override fun onMenuItemSelected(menuItem: MenuItem): Boolean {
return when (menuItem.itemId) {
R.id.settings -> {
Toast.makeText(this@MainActivity, "Settings...", Toast.LENGTH_SHORT).show()
true
}
else -> false
}
}
})

Adding menu from Fragment

override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
// Add options menu to the toolbar
requireActivity().addMenuProvider(object : MenuProvider {
override fun onCreateMenu(menu: Menu, menuInflater: MenuInflater) {
menuInflater.inflate(R.menu.main_menu, menu)
}
override fun onMenuItemSelected(menuItem: MenuItem): Boolean {
return when (menuItem.itemId) {
R.id.settings -> {
true
}
else -> false
}
}
}, viewLifecycleOwner)
}

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

Published in ProAndroidDev

The latest posts from Android Professionals and Google Developer Experts.

Written by Nav Singh

Google Developer Expert for Android | Mobile Software Engineer at Manulife | Organizer at GDG Montreal

Responses (1)