简体   繁体   中英

Handling back button with Android Navigation with two navigation graphs

I have created a small sample app to test out the android navigation library. The general idea is that I want two tabs with their own navigation graph.

My main activity layout contains a BottomNavigationView with two NavHost s.

The ButtonNavigationView click listener takes care of showing one NavHost or the other and also calling NavigationUI.setupActionBarWithNavController with the selected controller to update the toolbar accordingly. Up navigation is working fine.

The problem I am facing right now is the back button.

There is a property app:defaultNavHost="true" which ensures that your NavHostFragment intercepts the system back button, but I want that to be on/off depending on the active graph. I couldn't find a way to change it :(

I know I can override onBackPressed() but I am trying to find a way for the library to do that work for me letting it know which graph is active.

As per the NavHostFragment source , all that app:defaultNavHost="true" does is call through to setPrimaryNavigationFragment() , which is how FragmentManager knows which child Fragment to send back button events to.

Therefore, when switching to a new Fragment, you can add setPrimaryNavigationFragment() to your FragmentTransaction to get the same behavior.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM