Reputation: 652
In an Android app, I'm using the Navigation components. In a couple of places, I have list/detail views. I'm using an AbstractListDetailFragment and have also tried SlidingPaneLayout. With AbstractListDetailFragment, it sets up an OnBackPressedCallback, while with SlidingPaneLayout, I provided an OnBackPressedCallback. I get the same behavior in both cases.
I have a structure like this: Start Fragment -> List Fragment -> Detail Fragment.
On a wide screen, everything is fine. However, on a narrow screen, if I'm on the Detail Fragment and hit the toolbar back button, it doesn't take me back to the List Fragment but instead goes back to the Start Fragment. The hardware back button seems to be caught by the OnBackPressedCallback and does the right thing, but the toolbar back button doesn't.
I can certainly catch R.id.home in the Detail Fragment, but with AbstractListDetailFragment, it doesn't know anything about the world it's in. It's just another fragment that received some arguments, and it does its thing with them. It doesn't know if it's side by side or not. To complicate things further, it's in its own navigation graph.
What's the right way to handle this?
Upvotes: 0
Views: 247
Reputation: 652
Adding this to detail fragment solves the issues:
val menuHost: MenuHost = requireActivity()
menuHost.addMenuProvider(
object : MenuProvider {
override fun onCreateMenu(menu: Menu, menuInflater: MenuInflater) {
}
override fun onMenuItemSelected(menuItem: MenuItem): Boolean {
if (menuItem.itemId == android.R.id.home) {
requireActivity().onBackPressedDispatcher.onBackPressed()
return true
}
return false
}
},
viewLifecycleOwner
)
Upvotes: 0