Skip to content Skip to sidebar Skip to footer

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 lo

Solution 1:

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.ktoverridefunonViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
    
        if(!appAuth.isAuthenticated()) {
            view.findNavController().navigate(R.id.action_global_loginFragment)
        }
    }
    

Solution 2:

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
             }

        }
    }

Solution 3:

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)
)

Post a Comment for "How To Implement Conditional Navigation In Navigation Architecture Components"