I have an Activity
with 3 EditText
s and a custom view which acts a specialised keyboard to add information into the EditText
s.
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?
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;
}
following methods may help you
Activity host = (Activity) view.getContext()
; andview.isFocused()
UPDATED
tailrec fun Context.getActivity(): Activity? = this as? Activity
?: (this as? ContextWrapper)?.baseContext?.getActivity()
thanks to @Westy92
Usage:
context.getActivity()
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;
}
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With