Step #3: Launching Our Activity

Now that we have declared that the activity exists and can be used, we can start using it.

Go into MainActivity and modify onCreate() to start AboutActivity if the user chooses the about menu item, by adding an onOptionsItemSelected() function:

  override fun onOptionsItemSelected(item: MenuItem) = when (item.itemId) {
    R.id.about -> {
      startActivity(Intent(this, AboutActivity::class.java))
      true
    }
    else -> super.onOptionsItemSelected(item)
  }

onOptionsItemSelected() will be called when the user taps on one of the action bar items. We get passed a MenuItem identifying the item that the user tapped on, and we can examine its itemId value and compare it to the IDs of the items that we put into the menu resource that we used to populate the action bar.

For the R.id.about menu item, we create an Intent, pointing at our new AboutActivity. Then, we call startActivity() on that Intent.

onOptionsItemSelected() returns a Boolean: true if we handled the event, false otherwise. So, in the R.id.about branch we return true, otherwise we chain to the superclass implementation and return whatever it returns.

If you run this app in a device or emulator, and you choose the About overflow item, the AboutActivity should appear, but empty, as we have not given the Toolbar or WebView any content yet.

Instead of using startActivity(), we could have added an <activity> element to our navigation graph and then used the Navigation component to start the activity. That has some advantages, but using the Navigation component to start an activity is very modern and not all that common. Using startActivity() is far more representative of how existing code with multiple activities starts another activity.


Prev Table of Contents Next

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