How to get Activity reference in View class?
Solution 1
It should be fine to just cast the context to Activity:
MyActivity myActivity = (MyActivity) getContext();
Solution 2
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.
Solution 3
Pass context in the Constructor of View class like this
View Class
public class DrawView extends View {
Context actContext;
public DrawView(Context context) {
super(context);
actContext=context;
}
}
and in Your activity class
DrawView drawView=new DrawView(this);
CoDe
Updated on July 08, 2020Comments
-
CoDe almost 4 years
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?
-
CoDe over 10 yearssame I did ...and it work for me...thanks
-
Renascienza over 9 yearsPlease observe that getContext() may not return the host activity on some scenarios, like appwidgets or when you inflate a view without add it on the container, for some reason.
-
Admin over 9 yearsIt may also return a ContextThemeWrapper, which cannot be cast to Activity.
-
Jan over 9 yearsTrue, thanks for the hint. Be carefull if you are outside of "ordinary" application context.
-
Andrew about 9 yearsUsually I do like that, works fine. Sometimes (in some situations) extra checks will be needed to avoid crash.
-
domenukk over 7 yearsThis is the best answer and exactly what I came here for. Thank you it saved me a lot of time.
-
Christian about 7 yearsThanks, I just replaced ((Activity) getContext()).runOnUiThread( (new Thread(new Runnable() { with getActivity().runOnUiThread( (new Thread(new Runnable() { and it works...
-
ono over 6 years@user153275 when would this happen?