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

问题描述 投票:0回答:4

我有这段代码,当单击适配器中的 viewHolder 项目时,我会显示对话框片段

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

最近我正在迁移到 Hilt,并且遇到类转换异常,看起来 Hilt 包装了上下文,但我无法获取父级 Activity 来获取所需的 FragmentManager 来显示对话框

android kotlin dagger-2 dagger-hilt
4个回答
28
投票

我阅读源代码找到了这个解决方案

FragmentComponentManager.findActivity(view.context) as Activity


18
投票

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

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

0
投票

就我而言,我的自定义视图位于库模块中,即:(“com.android.library”),并且我在我的应用程序模块中使用 hilt,即:(“com.android.application”),因为这是我的应用程序正在崩溃。因为我在应用程序模块中使用 Hilt 库,并且上下文实例是由 Hilt 库创建的。我找不到fragmentManger。

因此,作为解决方法,我必须在库模块中添加 Hilt,然后使用下面的代码来查找 FragmentManger

private FragmentManager getFragmentManager(@NonNull Context mContext) {
        if (mContext instanceof AppCompatActivity) {
            return ((AppCompatActivity) mContext).getSupportFragmentManager();
        } else if (mContext instanceof ContextThemeWrapper) {
            return getFragmentManager(((ContextThemeWrapper) mContext).getBaseContext());
        }
// below if clause is for hilt library
 else if (mContext instanceof ViewComponentManager.FragmentContextWrapper) {
            return getFragmentManager(((ViewComponentManager.FragmentContextWrapper) mContext).getBaseContext());
        }
        return null;
    } 

如果是这种情况希望这可以帮助别人。

快乐编码。


0
投票
Please be sure to answer the question. Provide details and share your research!

但要避免……

Asking for help, clarification, or responding to other answers.
Making statements based on opinion; back them up with references or personal experience.    Please be sure to answer the question. Provide details and share your research!

但要避免……

Asking for help, clarification, or responding to other answers.
Making statements based on opinion; back them up with references or personal experience.    Please be sure to answer the question. Provide details and share your research!

但要避免……

Asking for help, clarification, or responding to other answers.
Making statements based on opinion; back them up with references or personal experience.
© www.soinside.com 2019 - 2024. All rights reserved.