Jetpack Compose - 底部弹出窗口对话框和ViewTreeLifecycleOwner存在问题

3
将英文翻译成中文:

将Jetpack Compose库更新到beta01后,我无法显示DialogFragment或BottomSheetDialogFragment。 看起来我的活动中找不到ViewTreeLifecycleOwner。此外,我尝试了一些可能的{{link1:解决方案}},但没有任何成功。

片段中的视图是通过以下方式膨胀的:

 override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        return inflater.inflate(
                R.layout.fragment_full_screen_layout, container, false
        ).apply {
            findViewById<ComposeView>(R.id.compose_view).setContent {...}

对话框片段正在显示:

DialogFragmentExample.newInstance().show(supportFragmentManager, null)

有人遇到类似的问题吗?请问有什么建议吗?
堆栈跟踪:
java.lang.IllegalStateException: ViewTreeLifecycleOwner not found from DecorView@409dd5d[MainActivity]
        at androidx.compose.ui.platform.WindowRecomposer_androidKt.createLifecycleAwareViewTreeRecomposer(WindowRecomposer.android.kt:214)
        at androidx.compose.ui.platform.WindowRecomposer_androidKt.access$createLifecycleAwareViewTreeRecomposer(WindowRecomposer.android.kt:1)
        at androidx.compose.ui.platform.WindowRecomposerFactory$Companion$LifecycleAware$1.createRecomposer(WindowRecomposer.android.kt:98)
        at androidx.compose.ui.platform.WindowRecomposerPolicy.createAndInstallWindowRecomposer$ui_release(WindowRecomposer.android.kt:151)
        at androidx.compose.ui.platform.WindowRecomposer_androidKt.getWindowRecomposer(WindowRecomposer.android.kt:199)
        at androidx.compose.ui.platform.AbstractComposeView.ensureCompositionCreated(ComposeView.android.kt:177)
        at androidx.compose.ui.platform.AbstractComposeView.onAttachedToWindow(ComposeView.android.kt:222)
2个回答

4
「我甚至没有使用 DialogFragment,却仍然遇到了相同的异常。 我的解决方法是从 Activity 中设置 ViewTreeLifecycleOwner:」
class MainActivity : AppCompatActivity() {
   override fun onCreate(savedInstanceState: Bundle?) {
      super.onCreate(savedInstanceState)

      ViewTreeLifecycleOwner.set(window.decorView, this)
      // setContent(...); add fragment using Compose view
   }
}

我目前正在使用以下库:
  • androidx.activity:activity-ktx:1.3.0-alpha04
  • androidx.fragment:fragment-ktx:1.3.1
  • androidx.compose.*:*:1.0.0-beta02

1
这个对我也起作用了,即使是在Compose运行时beta03下,我也没有使用对话框片段,而是使用带有片段的底部导航视图。 - Oscar Gallon

2
根据 Fragment 1.3.1 发布说明

现在,DialogFragment 中的对话框可以通过其 DecorView 访问 ViewTree 所有者,确保 DialogFragment 可以与 ComposeView 一起使用。 (Ib9290, b/180691023)

因此,您应确保升级到 Fragment 1.3.1:

implementation "androidx.fragment:fragment-ktx:1.3.1"

我尝试过快照版本构建,但那不成功,但这个可以!你救了我的一天,非常感谢! - lbasek

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接