【问题标题】:dagger.hilt.android.internal.managers.ViewComponentManager$FragmentContextWrapper cannot be cast to android.app.Activitydagger.hilt.android.internal.managers.ViewComponentManager$FragmentContextWrapper 无法转换为 android.app.Activity
【发布时间】:2020-10-13 18:51:11
【问题描述】:

我正在使用具有一些自定义视图实现的第三方库。在实现中,他们调用Utils.showSoftKeyboard(context as Activity)。这与将片段用作 @AndroidEntryPoint 一起导致以下异常:

java.lang.ClassCastException: dagger.hilt.android.internal.managers.ViewComponentManager$FragmentContextWrapper cannot be cast to android.app.Activity.

有没有办法在不改变第三方库的情况下解决这个问题?

【问题讨论】:

    标签: android kotlin dagger-hilt


    【解决方案1】:

    如果第三方库有问题跟踪器,最好提出有关此问题的问题。不能保证 ViewcontextActivity:自定义视图中的 android:theme 属性或任何祖先都可能很容易地导致相同的问题。

    如果您没有在片段中扩充任何 @AndroidEntryPoint 视图,则可以通过直接从活动上下文中获取 LayoutInflater 来解决此问题。

        override fun onCreateView(
            inflater: LayoutInflater,
            container: ViewGroup?,
            savedInstanceState: Bundle?
        ): View? {
            val baseInflater = LayoutInflater.from(requireActivity()) // NOT context
            // ...
        }
    

    【讨论】:

      【解决方案2】:

      没有 Hilt 依赖,我们可以访问父活动,如下所示

      (上下文作为 ContextWrapper).baseContext

      【讨论】:

        【解决方案3】:

        您的问题可能已经晚了,但这里有一个解决方案可能会帮助其他遇到同样问题的人。 您基本上应该在尝试强制转换之前检查上下文类型。

          val mContext = if (context is ViewComponentManager.FragmentContextWrapper)
                    context.baseContext
                else
                    context
        

        灵感来自this 答案。

        【讨论】:

          猜你喜欢
          • 2019-01-09
          • 2014-06-26
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多