In the new Navigation architecture component, how to implement conditional navigation?
Currently I have a single activity with LoginFragment and HomeFragment. Based on a
This is how I deal with conditional navigation :
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)
}
}
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
}
}
}