I created an custom view and there require Activity reference to perform some Handler related operation. I have idea about getContext() is a way to get Context but is there any way to get Activity reference for same?
It should be fine to just cast the context to Activity:
MyActivity myActivity = (MyActivity) getContext();
Casting getContext() to Activity (e.g. (Activity)getContext();) may not always return an Activity object if your View is not called from an Activity context.
So for that,
public Activity getActivity() {
Context context = getContext();
while (context instanceof ContextWrapper) {
if (context instanceof Activity) {
return (Activity)context;
}
context = ((ContextWrapper)context).getBaseContext();
}
return null;
}
"while" is used to bubble up trough all the base context, till the activity is found, or exit the loop when the root context is found. Cause the root context will have a null baseContext, leading to the end of the loop.
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