Skip to content

Instantly share code, notes, and snippets.

Last active March 21, 2022 14:40
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
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
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