如何避免静电方面的参考,当我需要使用一个活动场景?
阅读本主题避免内存泄漏的一些怀疑引起。
After read this topic avoiding memory leaks some doubts arouse.
如果我需要使用一个活动环境(例如:膨胀在视图中 PopupWindow
类来说明一个弹出),我怎么可以容纳实际活动的情况下做它?如果我需要避免静态上下文引用做的唯一途径是建立在我的类中的属性?和所有其他类,我需要实际的活动方面,我需要做呢?
If I need to use an activity context (example: inflate a view in a PopupWindow
class to show a popup) how can I hold the context of actual activity to do it? If I need to avoid a static context reference the only way to do it is creating an attribute in my class? And all the other classes I'll need the actual activity context I need to do it?
更新 -
我想在不继承的上下文,就像我在我的应用程序类的应用程序上下文有 getApplicationContext()称为静态方法$使用多个类使用这个实际活动背景C $ C>声明。这种方法遵循Singleton设计模式和正常工作。
I want to use this actual activity context in many classes that don't inherited Context, like I use with the application Context in my Application class that has a static method called getApplicationContext()
declared. This method follows the Singleton Design Pattern and works fine.
从code你在评论中联工作,为什么不能做到这一点:
Working from the code you linked in the comments, why not do this:
//my main activity
public class ExampleStaticReferenceActivity extends Activity {
//...
public void methodCalledWhenUserPressesButton(){
LinearLayout masterLayout = (LinearLayout) findViewById(R.id.masterLayout);
//now passing a reference to the current activity - elevine
masterLayout.addView(ButtonCreator.createButton(this));
}
}
//this class is in another package
public class ButtonCreator {
//added a Context parameter - elevine
public static Button createButton(Context context) {
Button button;
button = new Button(context);
//... some configurations for button
return button;
}
}