Step #8: Loading Our Options

Simply defining res/menu/actions.xml is insufficient. We need to actually tell Android to use what we defined in that file and show it in our Toolbar.

Once again, there are a few ways of doing this. For this book, we are going to use our Toolbar as the action bar. This is the simplest way to have multiple fragments all contribute to the Toolbar. In particular, it is the simplest way to have those fragments’ contributions come and go as the fragments themselves come and go.

To do that, add a setSupportActionBar() call to the bottom of onCreate() of MainActivity:

  override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)

    val binding = ActivityMainBinding.inflate(layoutInflater)

    setContentView(binding.root)
    setSupportActionBar(binding.toolbar)
  }

This tells AppCompatActivity that we want to use our Toolbar in the role of the activity’s action bar. binding.toolbar is a reference to the Toolbar widget from our layout, courtesy of view binding.

Then, add this function to MainActivity

  override fun onCreateOptionsMenu(menu: Menu): Boolean {
    menuInflater.inflate(R.menu.actions, menu)

    return super.onCreateOptionsMenu(menu)
  }

This is how you contribute toolbar buttons, overflow menu items, and other things to the activity’s action bar. The “options menu” name is a reference to the original Android UI (from Android 1.0).

Here, just as we used a LayoutInflater with ActivityMainBinding to inflate a layout resource, we use a MenuInflater to inflate a menu resource, pouring its contents into the supplied Menu object. We then chain to the superclass, just in case some superclass also wants to put things in the action bar.


Prev Table of Contents Next

This book is licensed under the Creative Commons Attribution-ShareAlike 4.0 International license.