我在使用childFragmentManager的片段内或使用supportFragmentManager的活动内显示一个对话框,在这个过程中,我想设置目标片段,如下所示:

val textSearchDialog = TextSearchDialogFragment.newInstance()
textSearchDialog.setTargetFragment(PlaceSearchFragment@this, 0)

But when running that code I get the error:

JAVAlang.IllegalStateException:片段

我不知道如何访问导航组件用来管理片段显示的FragmentManager,有什么解决方案吗?

推荐答案

Update: as part of Navigation 2.3.0, Navigation adds explicit support for returning a result with a specific section on returning a result from a Dialog destination as an alternative to using a shared ViewModel.

Previous answer:

The recommended pattern for communicating between Fragments with the Navigation Architecture Components is via a shared ViewModel - a ViewModel that lives at the Activity level achieved by retrieving the ViewModel using ViewModelProvider(getActivity())

As per the documentation, this offers a number of benefits:

  • The activity does not need to do anything, or know anything about this communication.
  • Fragments don't need to know about each other besides the SharedViewModel contract. If one of the fragments disappears, the other one keeps working as usual.
  • 每个片段都有自己的生命周期,不受另一个片段生命周期的影响.如果一个片段替换了另一个片段,UI将继续工作,没有任何问题.

您还可以使用navigation graph scoped ViewModel在比整个活动更小的范围内共享ViewModel.

Kotlin相关问答推荐

外键是主键的一部分,但不是索引的一部分.房间

Gradle Jooq配置自定义生成器

在intellij中使用kotlin符号和floordiv

如何为集成测试配置Gradle JVM测试套件?

在调用父构造函数之前重写类属性

Kotlin接口方法默认值&;可传递依赖项

如何优雅地声明一个StateFlow?

将 java Optional 转换为 Kotlin Arrow Option

TestContainers PostgreSQLContainer 与 Kotlin 单元测试:Not enough information to infer type variable SELF

判断 AAR 元数据值时发现的一个或多个问题:

对列表中数字的子集求和

jetpack compose 将参数传递给 viewModel

如何使 TextInputEditText 只读?

如何使用 Coil 从 URL 获取位图?

如何在 Kotlin 文件中的 Android Studio 中控制何时将 Imports 替换为通配符

Intellij 显示 build.gradle.kts 中的每一行都是红色的

Kotlin内联扩展属性

Kotlin 扩展函数 - 覆盖现有方法

Kotlin,什么时候按map授权?

在 Kotlin 中声明 Byte 会出现编译时错误The integer literal does not conform to the expected type Byte