![](/img/trans.png)
[英]Navigate from Jetpack Compose to Fragment and from Fragment to Jetpack Compose Screen
[英]Navigate from compose to Fragment
我想从撰写导航到片段。 我在 compose 中定义了一个 NavHost:
NavHost(
navController = navController,
startDestination = DrawerScreen.Screen2.route
) {
composable(DrawerScreen.Screen1.route) {
navController.navigate(R.id.screen_one)
}
composable(DrawerScreen.Screen2.route) {
Screen2(
openDrawer = {
openDrawer()
}
)
}
}
简单片段:
@AndroidEntryPoint
class ScreenOneFragment: Fragment() {
@Nullable
override fun onCreateView(
inflater: LayoutInflater,
@Nullable container: ViewGroup?,
@Nullable savedInstanceState: Bundle?
): View {
val view: View = inflater.inflate(R.layout.screen_one, container, false)
return view
}
}
但是,当我尝试导航时,出现以下异常:
java.lang.IllegalArgumentException: Navigation action/destination com.test/screenOne cannot be found from the current destination Destination(0x2b264dff) route=ScreenOne
这是我的导航xml:
<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/mobile_navigation"
app:startDestination="@id/screenOne">
<fragment
android:id="@+id/screenOne"
android:name="com.test.ScreenOne"
android:label="ScreenOne" />
</navigation>
是否可以从撰写导航到片段?
根据互操作性文档:
如果您想在 Compose 中使用 Navigation 组件,您有两种选择:
使用片段的导航组件定义导航图。
使用 Compose 目标在 Compose 中定义一个导航图和一个 NavHost。 只有当导航图中的所有屏幕都是可组合的时,这才有可能。
所以不,如果您使用的是NavHost
,则无法导航到片段目的地(反之亦然:如果您使用的是NavHostFragment
,则无法导航到composable
的目的地:两个世界都不知道对方)。
实际上听起来像是您想向 Compose 添加一个 Fragment 。 这将允许您的所有目的地在您的单个NavHost
中成为composable
的目的地,但让一个屏幕完全由一个片段(您的ScreenOne
)实现。
composable(DrawerScreen.Screen1.route) {
// Assumes you have a layout with a FragmentContainerView
// that uses android:name="com.test.ScreenOneFragment"
AndroidViewBinding(ScreenOneLayoutBinding::inflate) {
val myFragment = fragmentContainerView.getFragment<ScreenOneFragment>()
// ...
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.