简体   繁体   中英

Navigation Architecture Component navigation with only a Context

Is it possible to get a NavigationController and perform navigation with only a Context? Right now it appears no. That will require such a major restructuring of our app that I feel I must be missing something.

If the user is logged out we need to navigate to the LoginFragment. This logout check happens at several places that are not an Activity or Fragment. For example the Authenticator that goes in the OkHttpClient.

Currently this works fine, because you can access the ApplicationContext from anywhere, and that is all you need to create an Intent, startActivity with it, and add a new Activity on top the backStack.

As per the Implementing Navigation documentation :

Note: The Navigation components are designed for apps that have one main activity with multiple Fragment destinations. The main activity hosts the navigation graph and is responsible for swapping destinations as needed. In an app with multiple activity destinations, each additional activity hosts its own navigation graph.

Therefore, no. There is no global NavController that exists for your entire app - each Activity would have its own NavController and associated navigation graph.

However, there's no requirement that you switch your entire app over to Navigation all at once. As per the Migrate to Navigation documentation , you could convert one Activity at a time, continuing to use a separate login activity for this particular case just as before.

This is helped by the built in support for <activity> destinations, which are destinations that when you navigate() to them, do a startActivity() call, rather than a FragmentTransaction . This would be useful if you have a 'Login' button in your UI that you'd want to tie to starting your login activity.

There are some very good reasons to move towards a Single Activity model though, as explained in the Single Activity: Why, When, and How talk , but the end of the talk does stress that:

If you find yourself contorting your own experience and it's not making sense to you, don't do it. If something is working, that's good. Keep it working. But if you're finding you're running into issues, you're having inconsistent behavior, or you want to do things like share ViewModels, maybe that's the time to think about moving towards a single Activity structure.

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