May I know, is it safe for me to always cast Context
to Activity
within a View
?
View {
Activity activity = (Activity)this.getContext();
}
So far, it works fine all the moment. I was wondering, is there any edge cases that the above code will fail?
As I know, It is not always safe because, the context also can be passed from os to a Service, BroadcastReceiver, etc. But, almost of case, that is not a problem. just check 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;
}
Technically, Views can be created with any Context (via the LayoutInflater
)
So unless you are super sure that your Views are only instantiated by Activities, I wouldn't suggest this. Doing this is not a clean idea.
While I can't think of such case, I think it is not such a great idea for two reasons:
View
?
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.