问题
In the new Navigation architecture component, how to implement conditional navigation?
Currently I have a single activity with LoginFragment and HomeFragment. Based on a certain login_flag, I used to call either fragment from the MainActivity. Since LoginFragment is called only once, I have set the startDestination to HomeFragment and the Navigation loads this HomeFragment. is there any way to check the login_flag before the Navigation loads the HomeFragment.
回答1:
You can add navigation listener inside your activity, and from there navigate to LoginFragment based on your conditions, like this:
findNavController(nav_host_fragment).addOnNavigatedListener { controller, destination ->
when(destination.id) {
R.id.HomeFragment-> {
if(someCondition) {
//Navigate to LoginFragment
}
}
}
回答2:
This is how I deal with conditional navigation :
- Set HomeFragment as the start destination
Create a global action for LoginFragment
<action android:id="@+id/action_global_loginFragment" app:destination="@id/loginFragment" app:launchSingleTop="false" app:popUpTo="@+id/nav_graph" app:popUpToInclusive="true" />
Perform conditional navigation inside
onViewCreated
:// HomeFragment.kt override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) if(!appAuth.isAuthenticated()) { view.findNavController().navigate(R.id.action_global_loginFragment) } }
来源:https://stackoverflow.com/questions/50493988/how-to-implement-conditional-navigation-in-navigation-architecture-components