How to get hosting Activity from a view?

mAndroid picture mAndroid · Nov 26, 2011 · Viewed 89k times · Source

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?

Answer

Gomino picture Gomino · Oct 6, 2015

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;
}