Compose-Screenshot icon indicating copy to clipboard operation
Compose-Screenshot copied to clipboard

Functionality broken after migrating to Hilt

Open bengarding opened this issue 2 years ago • 2 comments

I recently migrated my dependency injections to Hilt, and this is no longer working for me. I tracked the problem down to ScreenshotExtension line 70. It was failing with this Exception:

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

I was able to get around it by using this SO answer. It would be nice to have a check in place for the context, perhaps something like:

val activityContext = if (context is Activity) {
    context
} else {
    (context as ContextWrapper).baseContext
}

bengarding avatar Jan 20 '23 14:01 bengarding

@bengarding, could you elaborate a bit how exactly you managed to solve this error? I'm also using Dagger-Hilt and even thought I've replicated the sample app almost to the dot, I cannot get the screenshot functionality to work:

Error:
android.view.ContextThemeWrapper cannot be cast to android.app.Activity

zkvvoob avatar May 14 '23 12:05 zkvvoob

@zkvvoob This is my onCreateView method for the Fragment that uses a screenshot:

override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View {
    // Use inflater with activity context rather than the ContextWrapper that is provided by Hilt.
    val baseInflater = LayoutInflater.from(requireActivity())
    return super.onCreateView(baseInflater, container, savedInstanceState)
}

bengarding avatar May 15 '23 13:05 bengarding