how to implement Conditional Navigation in navigation architecture components

戏子无情 提交于 2019-12-04 20:09:07

问题


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.


回答1:


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
             }

        }
    }



回答2:


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


来源:https://stackoverflow.com/questions/50493988/how-to-implement-conditional-navigation-in-navigation-architecture-components

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!