mus*_*ikk 8 android android-fragments android-architecture-navigation android-jetpack-compose
We have a legacy app that we start migrating to Jetpack Compose. The app has a single activity, uses Navigation component with a navigation XML graph to navigate between fragments.
We are following this approach:
Now, say we had Fragment1 containing some action to navigate to Fragment2. In the original code we would call the following in Fragment1:
NavHostFragment.findNavController(this).navigate(directionToFragment2)
Run Code Online (Sandbox Code Playgroud)
When creating a composable to replace Fragment1 UI, how can we implement the navigation from this composable to Fragment2? In the composable we can call:
val navController = rememberNavController()
Run Code Online (Sandbox Code Playgroud)
但这似乎是与片段使用的导航控制器不同的导航控制器。有没有一种方法可以从可组合项访问与片段使用的导航控制器相同的导航控制器?
我们目前看到的唯一替代方案是将 Fragment 的导航控制器作为参数传递给可组合项,但它看起来不太正确。
ian*_*ake 12
你是对的,你不能使用- 这将创建一个仅适用于可组合目的地的rememberNavController()全新嵌套。NavController
根据测试指南,强烈建议避免直接引用任何可 NavController组合项本身(即可HomeScreen组合项)中的任何内容。相反,建议传递一个 lambda,您的可组合项在需要导航时可以触发该 lambda。
setContent然后,您的 Fragment(调用您的 的那个ComposeView)将负责实现该 lambda 并调用NavHostFragment.findNavController(this).navigate(directionToFragment2).
作为一种(不太推荐的)替代方案,您还可以使用LocalView.current.findNavController()Fragments 在视图级别填充NavController并LocalView指向ComposeView托管您的可组合项。
| 归档时间: |
|
| 查看次数: |
5581 次 |
| 最近记录: |