While the previous answer (which is ContextWrapper
-aware) is indeed the correct one,
I’d like to provide a more idiomatic implementation to copy-paste.
fun Context.getActivity(): AppCompatActivity? = when (this) {
is AppCompatActivity -> this
is ContextWrapper -> baseContext.getActivity()
else -> null
}
As ContextWrapper
s can’t possibly wrap each other significant number of times, recursion is fine here.