Jetpack Compose升级beta01后BottomSheetDialogFragment报ViewTreeLifecycleOwner未找到
Compose升级beta01后Dialog/BottomSheet崩溃适配问题
问题背景
将Jetpack Compose库升级至beta01版本后,DialogFragment、BottomSheetDialogFragment类组件无法正常弹出展示。
排查后定位到直接报错原因为:从Activity的DecorView中无法检索到绑定的ViewTreeLifecycleOwner,尝试过社区流传的各类通用适配方案后问题依旧存在。
现有业务逻辑片段
Fragment视图加载实现
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 { ... } } }
Dialog触发调用
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)
可落地的排查与解决方向
- 校验宿主Activity的继承链路:确保所有承载页面的Activity最终继承自
androidx.activity.ComponentActivity且对应依赖版本不低于1.2.0,更低版本的Activity基类不会自动向DecorView注入ViewTreeLifecycleOwner、ViewTreeViewModelStoreOwner等Compose运行时必需的锚点对象 - 依赖版本对齐校验:确认
androidx.activity:activity、androidx.fragment:fragment、androidx.compose.ui:ui三个核心库的版本处于同一兼容线,跨版本混用会直接导致ViewTree上的锚点传递链路断裂 - Dialog组件特殊适配:Dialog类窗口持有独立的DecorView,和宿主Activity的DecorView不属于同一ViewTree层级,Compose beta01版本不会自动向Dialog的DecorView注入生命周期锚点,需要在DialogFragment的
onCreate方法中手动完成绑定:手动适配参考代码
override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) val dialogDecorView = dialog?.window?.decorView ?: return // 为Dialog独立的DecorView注入必需的锚点对象 ViewTreeLifecycleOwner.set(dialogDecorView, this) ViewTreeViewModelStoreOwner.set(dialogDecorView, this) ViewTreeSavedStateRegistryOwner.set(dialogDecorView, this) } - 视图加载时机校验:不要在视图刚完成inflate、还未attach到窗口的时候就提前给ComposeView调用
setContent,过早的初始化会导致Compose运行时向上追溯ViewTree锚点时无法找到完整的绑定链路
内容的提问来源于stack exchange,提问作者lbasek
相关产品推荐
相关产品推荐

