Skip to content

Instantly share code, notes, and snippets.

@kibotu
Last active March 21, 2022 14:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kibotu/8211a2dfc8ea0f41fcb7f9a79a87b1ff to your computer and use it in GitHub Desktop.
Save kibotu/8211a2dfc8ea0f41fcb7f9a79a87b1ff to your computer and use it in GitHub Desktop.
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
}
@kibotu
Copy link
Author

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