title: Show confirmation on back/up in Fragment with Navigation Architecture Component
body: <p>I am using the Navigation Architecture Component for Android.</p>
  
  <p>For one of my fragments I wish to intercept "back" and "up" navigation, so that I can show a confirmation dialog before discarding any unsaved changes by the user. (Same behavior as the default Calendar app when you press back/up after editing event details)</p>
  
  <p>My current approach (untested) is as follows:</p>
  
  <p>For "up" navigation, I override <code>onOptionsItemSelected</code> on the fragment:</p>
  
  <pre><code>override fun onOptionsItemSelected(item: MenuItem?): Boolean {
      if(item?.itemId == android.R.id.home) {
          if(unsavedChangesExist()) {
              // TODO: show confirmation dialog
              return true
          }
      }
      return super.onOptionsItemSelected(item)
  }
  </code></pre>
  
  <p>For "back" navigation, I created a custom interface and callback system between the fragment and its activity:</p>
  
  <pre><code>interface BackHandler {
      fun onBackPressed(): Boolean
  }
  
  class MainActivity : AppCompatActivity() {
      ...
  
      val backHandlers: MutableSet&lt;BackHandler&gt; = mutableSetOf()
  
      override fun onBackPressed() {
          for(handler in backHandlers) {
              if(handler.onBackPressed()) {
                  return
              }
          }
          super.onBackPressed()
      }
  
      ...
  }
  
  class MyFragment: Fragment(), BackHandler {
      ...
  
      override fun onAttach(context: Context) {
          super.onAttach(context)
          if (context is MainActivity) {
              context.backHandlers.add(this)
          }
      }
  
      override fun onDetach() {
          (activity as? MainActivity)?.backHandlers?.remove(this)
          super.onDetach()
      }
  
      override fun onBackPressed(): Boolean {
          if(unsavedChangedExist()) {
              // TODO: show confirmation dialog
              return true
          }
      }
  
      ...
  }
  </code></pre>
  
  <p>This is all pretty gross and boilerplatey for such a simple thing. Is there a better way?</p>