how to implement Conditional Navigation in navigation architecture components

后端 未结 2 2053
无人及你
无人及你 2021-02-08 14:17

In the new Navigation architecture component, how to implement conditional navigation?

Currently I have a single activity with LoginFragment and HomeFragment. Based on a

相关标签:
2条回答
  • 2021-02-08 14:24

    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)
          }
      }
      
    0 讨论(0)
  • 2021-02-08 14:34

    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
                 }
    
            }
        }
    
    0 讨论(0)
提交回复
热议问题