Hi! TIL where you are using hilt there is new `Fra...
# dagger
r
Hi! TIL where you are using hilt there is new
FragmentContextWrapper
so calling any
.context
on any view that is in the fragment returns
FragmentContextWrapper
instead of an
Activity
. We have a
Context
extension:
Copy code
fun Context.navigateWithDirections(
    navDirections: NavDirections,
    navOptions: NavOptions? = NavOptions.Builder()
        .setEnterAnim(R.anim.nav_default_enter_anim)
        .setExitAnim(R.anim.nav_default_exit_anim)
        .setPopEnterAnim(R.anim.nav_default_pop_enter_anim)
        .setPopExitAnim(R.anim.nav_default_pop_exit_anim)
        .build()
) {
    (this as? Activity)?.findNavController(R.id.nav_host_fragment)?.navigate(navDirections, navOptions)
}
and this
(this as? Activity)?
check doesn’t pass cause there is
FragmentContextWrapper
. In the docs I see
Copy code
* Do not use except in Hilt generated code!
So my question is. Is there any other way I can get the activity context instead of this wrapper?
s
Not sure if there is already one such method, but you can traverse up the Context chain by repeatedly calling
.baseContext
(if that is the correct name) until that context
is Activity
.
j
It was never guaranteed to return the activity in the first place. Things like an
android:theme
attribute or simply using a
ContextWrapper
in a view before inflating children would break that assumption. You've always needed to perform a walk up the context hierarchy for accurate results, and you may never even reach an activity if the view is hosted in something like a floating window.
đź‘Ť 1
h
Is this true for both
getContext()
and
getActivity()
in a fragment?