Skip to content

Instantly share code, notes, and snippets.

Last active March 21, 2022 14:40
What would you like to do?
Jetpack Compose get activity in Composable from LocalContext.
// val activity = LocalContext.current.findActivity()
tailrec fun Context.findActivity(): AppCompatActivity? = when (this) {
is AppCompatActivity -> this
is ContextWrapper -> baseContext.findActivity()
else -> null
Copy link

kibotu commented Jan 9, 2022

If you prefer non recursive

    var currentContext = this
    while (currentContext is ContextWrapper) {
        if (currentContext is Activity) {
            return currentContext
        currentContext = currentContext.baseContext
    return null

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment