Hilt ClassCastException:无法将 ViewComponentManager$FragmentContextWrapper 转换为 AppCompatActivity

Moh*_*him 5 android kotlin dagger-2 dagger-hilt

我有这个代码,当单击 Adapter 中的 viewHolder 项目时,我会在其中显示 Dialog Fragment

 SpecialRequestNotFoundBottomSheetDialog {
            requestItem?.specialRequestEntity?.id?.let { id -> onCancelReasonsSelected(id, it) }
        }.show(itemView.context as AppCompatActivity).supportFragmentManager)
Run Code Online (Sandbox Code Playgroud)

最近我正在迁移到 Hilt 并且我得到了类转换异常,看起来像 Hilt 包装了上下文,我无法让父Activity获得所需的FragmentManager来显示 Dialog

Moh*_*him 11

我可能会通过检查 Context 类型并获取 BaseContext 来找到解决此崩溃的方法。这是我现在正在使用的。我不知道使用Hilt是否有更好的方法。

private fun activityContext(): Context? {
    val context = itemView.context
    return if (context is ViewComponentManager.FragmentContextWrapper) {
        context.baseContext
    } else context
}
Run Code Online (Sandbox Code Playgroud)


小智 7

我阅读源代码找到这个解决方案 FragmentComponentManager.findActivity(view.context) as Activity