17

I'm using a third-party library that has some custom view implementations. In the implementation, they call Utils.showSoftKeyboard(context as Activity). This, along with using the fragment as an @AndroidEntryPoint causes the following exception:

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

Is there any way to fix this without altering the third-party library?

Carter Hudson
  • 1,176
  • 1
  • 11
  • 23

3 Answers3

12

If the third-party library has an issue tracker, it's a good idea to raise an issue about this. There is no guarantee that the context of a View is an Activity: the same problem can be caused just as easily by an android:theme attribute in the custom view or any ancestor.

If you don't inflate any @AndroidEntryPoint views in your fragment, you can work around this by getting a LayoutInflater directly from the activity context.

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        val baseInflater = LayoutInflater.from(requireActivity()) // NOT context
        // ...
    }
Nitrodon
  • 3,089
  • 1
  • 8
  • 15
5

Without Hilt Dependencies we can access parent activity as below

(context as ContextWrapper).baseContext

Shekhar Reddy
  • 81
  • 1
  • 2
2

It might be late for your problem but here's a solution which might help others having the same problem. You basically should check the context type before trying to cast it.

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

Inspired by this answer.

moonkin
  • 353
  • 1
  • 10