问题描述
在新的Navigation体系结构组件中,如何实现条件导航?
In the new Navigation architecture component, how to implement conditional navigation?
目前,我只有一个与LoginFragment和HomeFragment有关的活动.基于特定的login_flag,我曾经从MainActivity调用任一片段.由于LoginFragment仅被调用一次,因此我将startDestination设置为HomeFragment,并且Navigation加载了此HomeFragment.在导航加载HomeFragment之前,有什么方法可以检查login_flag.
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.
推荐答案
这就是我处理条件导航:
- Set HomeFragment as the start destination
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" />
在onViewCreated
内进行条件导航:
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)
}
}
这篇关于如何在导航体系结构组件中实现条件导航的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!