gpt4 book ai didi

android - 从 compose 导航到 Fragment

转载 作者:行者123 更新时间:2023-12-02 15:51:34 69 4
gpt4 key购买 nike

我想从 compose 导航到 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()
}
)
}
}

简单 fragment :

@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 导航到 Fragment?

最佳答案

根据 Interopability docs :

If you want to use the Navigation component with Compose, you have two options:

  • Define a navigation graph with the Navigation component for fragments.

  • Define a navigation graph with a NavHost in Compose using Compose destinations. This is possible only if all of the screens in the navigation graph are composables.

所以不,如果您使用的是 NavHost,则无法导航到 fragment 目标(反之亦然:如果您使用的是 NavHostFragment,则可以'不要导航到一个可组合目的地:两个世界都不知道另一个世界)。

它实际上听起来像是你想要 add a Fragment to Compose .这将允许您的所有目的地成为您的单个 NavHost 中的可组合目的地,但让一个屏幕完全由 fragment 实现(您的 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>()
// ...
}

关于android - 从 compose 导航到 Fragment,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72427616/

69 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com