Jetpack Compose - BottomSheetDialogFragment 和 ViewTreeLifecycleOwner 的问题

Jetpack Compose - Problem with BottomSheetDialogFragment and ViewTreeLifecycleOwner

将 Jetpack Compose 库更新为 beta01 后,我无法显示 DialogFragment 或 BottomSheetDialogFragment。 在我的 activity 中似乎找不到 ViewTreeLifecycleOwner。另外,我尝试了几个可能的 solutions 但没有任何成功。

片段中的视图膨胀为:

 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.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)

根据 Fragment 1.3.1 release notes:

Dialogs within a DialogFragment can now get access to ViewTree owners through their DecorView, ensuring that DialogFragment can be used with ComposeView. (Ib9290, b/180691023)

所以你应该确保升级到 Fragment 1.3.1:

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

我什至没有使用 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