是否可以使用Android导航架构组件(Android Jetpack)有条件地设置startDestination?
作者:互联网
我从Android Jetpack使用Navigation在屏幕之间导航.
现在我想动态设置startDestination.
我有一个名为MainActivity的Activity
还有两个片段,FragmentA& FragmentB.
var isAllSetUp : Boolean = // It is dynamic and I’m getting this from Preferences.
If(isAllSetUp)
{
// show FragmentA
}
else
{
//show FragmentB
}
我想使用Navigation Architecture Component设置上面的流程.目前我使用startDestionation如下所示,但它不符合我的要求.
<navigation xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/lrf_navigation"
app:startDestination="@id/fragmentA">
<fragment
android:id="@+id/fragmentA"
android:name="com.mindinventory.FragmentA"
android:label="fragment_a"
tools:layout="@layout/fragment_a" />
</navigation>
是否可以使用Android导航架构组件有条件地设置startDestination?
解决方法:
最后,我得到了一个解决方案…
将下面的代码放在Activity的onCreate()方法中.
Kotlin code
val navHostFragment = home_nav_fragment as NavHostFragment
val inflater = navHostFragment.navController.navInflater
val graph = inflater.inflate(R.navigation.nav_main)
graph.setDefaultArguments(intent.extras)
graph.startDestination = R.id.fragment1
//or
//graph.startDestination = R.id.fragment2
navHostFragment.navController.graph = graph
Java code
NavHostFragment navHostFragment = (NavHostFragment) getSupportFragmentManager().findFragmentById(R.id.home_nav_fragment); // Hostfragment
NavInflater inflater = navHostFragment.getNavController().getNavInflater();
NavGraph graph = inflater.inflate(R.navigation.nav_main);
graph.setDefaultArguments(getIntent().getExtras());
graph.setStartDestination(R.id.fragment1);
navHostFragment.getNavController().setGraph(graph);
navHostFragment.getNavController().getGraph().setDefaultArguments(getIntent().getExtras());
NavigationView navigationView = findViewById(R.id.navigationView);
NavigationUI.setupWithNavController(navigationView, navHostFragment.getNavController());
标签:android,android-jetpack,android-architecture-navigation 来源: https://codeday.me/bug/20190928/1828257.html