How to get Activity reference in View class?

42,455

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);
Share:
42,455
CoDe
Author by

CoDe

Updated on July 08, 2020

Comments

  • CoDe
    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
    CoDe over 10 years
    same I did ...and it work for me...thanks
  • Renascienza
    Renascienza over 9 years
    Please 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
    Admin over 9 years
    It may also return a ContextThemeWrapper, which cannot be cast to Activity.
  • Jan
    Jan over 9 years
    True, thanks for the hint. Be carefull if you are outside of "ordinary" application context.
  • Andrew
    Andrew about 9 years
    Usually I do like that, works fine. Sometimes (in some situations) extra checks will be needed to avoid crash.
  • domenukk
    domenukk over 7 years
    This is the best answer and exactly what I came here for. Thank you it saved me a lot of time.
  • Christian
    Christian about 7 years
    Thanks, I just replaced ((Activity) getContext()).runOnUiThread( (new Thread(new Runnable() { with getActivity().runOnUiThread( (new Thread(new Runnable() { and it works...
  • ono
    ono over 6 years
    @user153275 when would this happen?