Step #5: Displaying the (Empty) Fragment

Now that we are displaying the app bar item, we can get control and show the presently-empty EditFragment.

First, add this edit() function to DisplayFragment:

  private fun edit() {
    findNavController().navigate(
      DisplayFragmentDirections.editModel(
        args.modelId
      )
    )
  }

As we did in RosterListFragment, we use findNavController() to get the NavController for the navigation graph associated with the DisplayFragment. Then, we use navigate() to go somewhere. Specifically, we use DisplayFragmentDirections.editModel() to invoke the action that we added to editFragment in the navigation graph. And, since editFragment requires an argument, we supply that model ID to editModel(), getting the modelId from our own args.

Then, add this onOptionsItemSelected() function to DisplayFragment:

  override fun onOptionsItemSelected(item: MenuItem): Boolean {
    when (item.itemId) {
      R.id.edit -> {
        edit()
        return true
      }
    }

    return super.onOptionsItemSelected(item)
  }

Here, if the MenuItem is our edit one, we call edit() and return true to indicate that we consumed the event. Otherwise, we chain to the superclass.

If you run the sample app now, and you click on one of the to-do items, and then click on the “edit” app bar item, you will be taken to the empty EditFragment.

If you press BACK when viewing the (empty) EditFragment, you will return to the DisplayFragment, and pressing BACK from there will return you to the list of to-do items.


Prev Table of Contents Next

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