Issue
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.
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)
}
Solution
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
}
Answered By - Zain
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.