Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get hosting Activity from a view?

I have an Activity with 3 EditTexts and a custom view which acts a specialised keyboard to add information into the EditTexts.

Currently I'm passing the Activity into the view so that I can get the currently focused edit text and update the contents from the custom keyboard.

Is there a way of referencing the parent activity and getting the currently focused EditText without passing the activity into the view?

like image 558
mAndroid Avatar asked Nov 26 '11 05:11

mAndroid


5 Answers

I just pulled that source code from the MediaRouter in the official support library and so far it works fine:

private Activity getActivity() {
    Context context = getContext();
    while (context instanceof ContextWrapper) {
        if (context instanceof Activity) {
            return (Activity)context;
        }
        context = ((ContextWrapper)context).getBaseContext();
    }
    return null;
}
like image 146
Gomino Avatar answered Nov 07 '22 06:11

Gomino


following methods may help you

  1. Activity host = (Activity) view.getContext(); and
  2. view.isFocused()
like image 20
dira Avatar answered Nov 07 '22 06:11

dira


UPDATED

tailrec fun Context.getActivity(): Activity? = this as? Activity
    ?: (this as? ContextWrapper)?.baseContext?.getActivity()

thanks to @Westy92

Usage:

context.getActivity()
like image 22
Vlad Avatar answered Nov 07 '22 06:11

Vlad


I took Gomino's answer and modified it to fit perfectly in myUtils.java so I can use it wherever and whenever I need. Hope someone finds it helpful :)

abstract class myUtils {
    public static Activity getActivity(View view) {
        Context context = view.getContext();
        while (context instanceof ContextWrapper) {
            if (context instanceof Activity) {
                return (Activity)context;
            }
            context = ((ContextWrapper)context).getBaseContext();
        }
        return null;
    }
}
like image 42
brownieGirl Avatar answered Nov 07 '22 07:11

brownieGirl


Just want to note that, if you know that your view is inside a Fragment, you can just do:

FragmentManager.findFragment(this).getActivity();

Call this from your onAttachedToWindow or onDraw, you can't call it earlier (e.g. onFinishInflate) or you will get an exception.

If you are not sure your view is inside a Fragment then refer to other answers e.g. Gomino, just wanted to throw it out there.

like image 42
Adam Burley Avatar answered Nov 07 '22 05:11

Adam Burley