Search code examples
androidandroid-lifecycle

Easy way to get current Activity, Fragment, LifeCycleOwner from within View?


When writing Views, ViewModels and LiveData are lifecycle aware. The ViewModel want's the current FragmentActivity, LiveData the current LifecycleOwner. You don't know in advance if your View will be wrapped or somewhat. So it requires a flexible function to to find the wanted context. I ended up with this two methods:

private FragmentActivity getFragmentActivity() {
    Context context = getContext();
    while (!(context instanceof FragmentActivity)) {
        context = ((ContextWrapper) context).getBaseContext();
    }
    return (FragmentActivity) context;
}

private LifecycleOwner getLifecycleOwner() {
    Context context = getContext();
    while (!(context instanceof LifecycleOwner)) {
        context = ((ContextWrapper) context).getBaseContext();
    }
    return (LifecycleOwner) context;
}

Now this is a lot of boilerplate code to put into each View. Is there a more easy way?

I don't want to use a customised View base class for this, as large hierarchy's are ugly. Composition on the other hand requires as much code as this solution.


Solution

  • you can find it lifecycle-runtime-ktx :

    fun View.findViewTreeLifecycleOwner(): LifecycleOwner? = ViewTreeLifecycleOwner.get(this)