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.
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)
}
}
I'd like to add that there is a codelab on developer.android.com for this purpose.
In all required fragments, you define a "next_action" (IDs obviously don't have to be unique) like this:
<action
android:id="@+id/next_action"
app:popUpTo="@id/home_dest">
</action>
Then, conditionally, you can set onClickListeners in your code:
view.findViewById<Button>(R.id.navigate_action_button)?.setOnClickListener(
Navigation.createNavigateOnClickListener(R.id.next_action, null)
)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With