【问题标题】:Jetpack Compose - Problem with BottomSheetDialogFragment and ViewTreeLifecycleOwnerJetpack Compose - BottomSheetDialogFragment 和 ViewTreeLifecycleOwner 的问题
【发布时间】:2021-03-11 17:19:18
【问题描述】:

将 Jetpack Compose 库更新为 beta01 后,我无法显示 DialogFragment 或 BottomSheetDialogFragment。 看起来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$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)

【问题讨论】:

    标签: android android-jetpack android-jetpack-compose


    【解决方案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

    【讨论】:

    • 即使使用 Compose 运行时 beta03,这个也对我有用,我也没有使用对话框片段,而是带有片段的底部导航视图
    【解决方案2】:

    根据Fragment 1.3.1 release notes

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

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

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

    【讨论】:

    • 我尝试了快照构建,但没有成功,但这有效!你拯救了我的一天,非常感谢!
    猜你喜欢
    • 1970-01-01
    • 2021-10-18
    • 1970-01-01
    • 1970-01-01
    • 2022-08-18
    • 2021-06-29
    • 2021-06-01
    • 2021-10-13
    • 2022-10-23
    相关资源
    最近更新 更多