Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jetpack navigation to a common destination

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?

like image 586
John Avatar asked Oct 22 '18 20:10

John


1 Answers

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

like image 67
Alex Avatar answered Nov 12 '22 19:11

Alex