Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to implement Conditional Navigation in navigation architecture components

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.

like image 308
Shashi Kiran Avatar asked May 23 '18 17:05

Shashi Kiran


2 Answers

This is how I deal with conditional navigation :

  1. Set HomeFragment as the start destination
  2. 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" />
    
  3. 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)
        }
    }
    
like image 51
maxbeaudoin Avatar answered Sep 17 '22 22:09

maxbeaudoin


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)
)
like image 30
cslotty Avatar answered Sep 16 '22 22:09

cslotty