[ACCEPTED]-Is it always safe to cast Context to Activity within View-android
Accepted answer
As I know, It is not always safe because, the 4 context also can be passed from os to a 3 Service, BroadcastReceiver, etc. But, almost 2 of case, that is not a problem. just check 1 with this code
if(context instanceof Activity)
and feel free to use.
I think you can use following snippet:
/**
* Get activity instance from desired context.
*/
public static Activity getActivity(Context context) {
if (context == null) return null;
if (context instanceof Activity) return (Activity) context;
if (context instanceof ContextWrapper) return getActivity(((ContextWrapper)context).getBaseContext());
return null;
}
0
Technically, Views can be created with any 4 Context (via the LayoutInflater
)
So unless you are super 3 sure that your Views are only instantiated 2 by Activities, I wouldn't suggest this. Doing 1 this is not a clean idea.
While I can't think of such case, I think 1 it is not such a great idea for two reasons:
- Why would you want to do that, when do you explicitly need Activity?
- What if tomorrow this will be changed, and there will be other context for
View
?
Source:
stackoverflow.com
More Related questions
Cookie Warning
We use cookies to improve the performance of the site. By staying on our site, you agree to the terms of use of cookies.