如何从另一个班级引用当前或主要活动

问题描述:

我经常发现自己需要访问需要引用某些活动的方法.例如,要使用getWindowManager,我需要访问一些Activity.但是,我使用这些方法的代码通常位于其他类中,而这些类均未引用活动.到目前为止,我要么存储了对主活动的引用,要么将某些活动的上下文传递给了类.有更好的方法吗?

I often find myself needing to access methods that require referencing some activity. For example, to use getWindowManager, I need to access some Activity. But often my code for using these methods is in some other class that has no reference to an activity. Up until now, I've either stored a reference to the main activity or passed the context of some activity to the class. Is there some better way to do this?

如果您已经具有有效的上下文,则只需使用以下命令: Activity activity = (Activity) context;

If you already have a valid context, just use this: Activity activity = (Activity) context;