【Android】Navigation动态设置Graph和Launch参数

需求

Activity和Fragment可以服用,不同的启动方式,Fragment调用栈不同

方案

不同的启动方式,通过代码动态设置,使用不同的NavGraph

注意

动态设置代码是在onCreate之后执行的

NavHost如果指定了Graph,在onCreate后会立刻启动,可能会造成启动两个Fragment栈

所以使用动态Graph方案的话,在NavHost中不能设置app:navGraph

动态设置代码
private fun setNavGraph() {
  // launch intent
  val purpose = intent.extras?.getString(AccountVerifyPurpose.KEY_PURPOSE)
  val bundle = Bundle()
  bundle.putString(AccountVerifyPurpose.KEY_PURPOSE, purpose)
  // choose nav graph
  val navHostFragment = supportFragmentManager.findFragmentById(R.id.nav_host) as NavHostFragment
  navController = navHostFragment.navController
  navController.setGraph(chooseNavGraph(purpose), bundle)
}

private fun chooseNavGraph(purpose: String) = when (purpose) {
  xxx -> R.navigation.nav_graph_xxx
  xxx -> R.navigation.nav_graph_xxx
  xxx -> R.navigation.nav_graph_xxx
  xxx -> R.navigation.nav_graph_xxx
  else -> R.navigation.nav_graph_xxx
}
共享数据

不同的Fragment如果想要共享数据的话,可以通过共享ActivityScope的ViewModel来实现

在Activity和Fragment中通过以下代码获取AccountCenterViewModel,拿到的将是同一份对象

private val accountViewModel by lazy {
  ViewModelProvider(this)[AccountCenterViewModel::class.java]
}
accountViewModel.account.value = xxx
private val accountViewModel by lazy {
  ViewModelProvider(requireActivity())[AccountCenterViewModel::class.java]
}
println(accountViewModel.account.value)

你可能感兴趣的:(android-疑难杂症研究,android,navigation,NavGraph,动态设置)