首页 > 解决方案 > Jetpack Compose - BottomSheetDialogFragment 和 ViewTreeLifecycleOwner 的问题

问题描述

将 Jetpack Compose 库更新为 后beta01,我无法显示 DialogFragment 或 BottomSheetDialogFragment。看起来ViewTreeLifecycleOwner在我的活动中找不到了。另外,我尝试了几种可能的解决方案,但都没有成功。

片段中的视图被夸大了:

 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)

标签: androidandroid-jetpackandroid-jetpack-compose

解决方案


我什至没有使用DialogFragment.

我的解决方法是设置ViewTreeLifecycleOwnerfrom Activity

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

推荐阅读