Reputation: 145
I've been using the new new Navigation-API in Jetpack and I've come across a problem that I can't find a satisfactory solution to.
Basically the app I'm creating has a large number of different fragments. Most of the fragments talk to a backend and when they do they can discover that their session has timed out. When this occurs I want to go to the login-fragment. The only way I've been able to do this is to create an action for every fragment with the destination pointing to the login screen. This is a lot of boiler plate that I would rather avoid. Is there a simpler way to do this?
Upvotes: 13
Views: 7783
Reputation: 554
I'd rather post another way that is more suitable for passing arguments and data:
// Navigation Component
implementation "androidx.navigation:navigation-fragment-ktx:$navigationVersion"
implementation "androidx.navigation:navigation-ui-ktx:$navigationVersion"
In nav_graph.xml add a global action as @Alex has been Posted or by right click On your fragment and add action -> Global as like below
Now in your Fragment which ganna go to this destination just call NavGraphDirections and find your global action like below
val action = NavGraphDirections.actionGlobalInternalLinkDispatcher()
findNavController().navigate(action)
actionGlobalInternalLinkDispatcher() is my Global distanition action find your case
val action = NavGraphDirections.actionGlobalInternalLinkDispatcher(myArgumentExample)
findNavController().navigate(action)
I suggest watching this on youtube it will be going to help Menu & Global Actions - Getting Started With Navigation Component #6
Upvotes: 0
Reputation: 9342
For this use case you can use global action. To create global action, select the desired destination in navigation graph. Right click and in the menu select ‘Add action’ and click on ‘Global’, this will create a global action inside your navigation graph root element:
<action android:id="@+id/action_global_signInFragment" app:destination="@id/signInFragment"/>
Now you can use global actions by calling navigation() method and passing it the id of the desired global action:
NavHostFragment.findNavController(this).navigate(R.id.action_global_signInFragment)
https://developer.android.com/topic/libraries/architecture/navigation/navigation-global-action
Upvotes: 14