Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get Activity reference in View class? [duplicate]

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?

like image 764
CoDe Avatar asked Oct 25 '13 08:10

CoDe


2 Answers

It should be fine to just cast the context to Activity:

MyActivity myActivity = (MyActivity) getContext();
like image 153
Jan Avatar answered Sep 28 '22 16:09

Jan


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.

like image 28
Arunendra Avatar answered Sep 28 '22 18:09

Arunendra