Skip to content
This repository has been archived by the owner on Nov 14, 2018. It is now read-only.

Get parent Activity from View #363

Closed
minsik-ai opened this issue Feb 27, 2018 · 11 comments
Closed

Get parent Activity from View #363

minsik-ai opened this issue Feb 27, 2018 · 11 comments

Comments

@minsik-ai
Copy link

I find this immensely useful when using MVVM pattern.

fun View.getActivity(): Activity? {
    var context = context
    while (context is ContextWrapper) {
        if (context is Activity) {
            return context
        }
        context = context.baseContext
    }
    return null
}

Please let me know what you think of it. Thanks.

@JakeWharton
Copy link
Contributor

I don't think we want to violate the scoping of views with this. Would we also have one for Dialog? What about views added directly to WindowManager that have neither an Activity or Dialog? The need to reach outside of your view into the enclosing container should be rare and I'm not sure we want to encourage it at this level.

@jaredsburrows
Copy link
Contributor

@trent-dev Are you getting this from the Android code base? Such as MediaRouteButton: https://android.googlesource.com/platform/frameworks/base/+/master/core/java/android/app/MediaRouteButton.java#163?

@minsik-ai
Copy link
Author

minsik-ai commented Mar 2, 2018

@jaredsburrows Yes. I found it from somewhere similar to code you linked.

@hameno
Copy link

hameno commented Mar 2, 2018

We have the following extension in our code:

fun Context.getActivityContext(): Activity = when (this) {
    is Activity -> this
    is ContextWrapper -> this.baseContext.getActivityContext()
    else -> throw IllegalArgumentException("Not an activity context")
}

I'm not super happy with the IllegalArgumentException but in our case it should never happen.

@JakeWharton
Copy link
Contributor

JakeWharton commented Mar 2, 2018 via email

@hameno
Copy link

hameno commented Mar 2, 2018

@JakeWharton Good point, a "tailrec" should fix that, right? I also get your point, it is not always safe to use.

@JakeWharton
Copy link
Contributor

JakeWharton commented Mar 2, 2018 via email

@JakeWharton
Copy link
Contributor

Going to close this because we don't want to recommend this as a general pattern. You should very rarely need to do this, but if you do it's fine to keep the code in your codebase only.

@jaredsburrows
Copy link
Contributor

@JakeWharton We should make a note to deprecate then remove methods in AOSP.

@JakeWharton
Copy link
Contributor

JakeWharton commented Mar 2, 2018 via email

@jaredsburrows
Copy link
Contributor

@JakeWharton Good.

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests

4 participants