1

So I'm using Android Navigation in my app, and I'm running into this case:

I have 2 fragments A -> B, now whenever the user navigate back from B -> A, I want to show an alert before the back event.

I've followed this answer, and got this solution:

// code on fragment B's onViewCreated()
requireActivity().onBackPressedDispatcher.addCallback(viewLifecycleOwner) {
    alert("Are you sure to quit?")
}

And this solution work well when I press the hardware back button, but when I press the back button on the Toolbar, the callback doesn't get called. Please help me, thank you.

enter image description here

Here my MainActivity's Navigation setup:

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    supportActionBar!!.setDisplayHomeAsUpEnabled(true)

    navController = findNavController(R.id.nav_host_fragment_container)
    appBarConfiguration = AppBarConfiguration(navController.graph)
    setupActionBarWithNavController(navController, appBarConfiguration)
}

override fun onSupportNavigateUp(): Boolean {
    return navController.navigateUp(appBarConfiguration) || super.onSupportNavigateUp()
}

override fun onOptionsItemSelected(item: MenuItem): Boolean {
    return item.onNavDestinationSelected(navController) || super.onOptionsItemSelected(item)
}
Zain
  • 37,492
  • 7
  • 60
  • 84

2 Answers2

1

You need to add code as below -

override fun onSupportNavigateUp(): Boolean {
    alert("Are you sure to quit?")
    return false
}
Priyanka
  • 1,791
  • 1
  • 7
  • 12
1

In fragment B in onCreateView enable options menu

setHasOptionsMenu(true)

And override onOptionsItemSelected

override fun onOptionsItemSelected(item: MenuItem): Boolean {
    if (item.itemId == android.R.id.home) { // ActionBar back/parent button is pressed
        // onBackPressed() // to return back to Fragment A
    }
    return true
}
Zain
  • 37,492
  • 7
  • 60
  • 84