如何避免静电方面的参考,当我需要使用一个活动场景? [英] How to avoid static context reference when I need to use a activity context?

查看:144
本文介绍了如何避免静电方面的参考,当我需要使用一个活动场景?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

阅读本主题避免内存泄漏的一些怀疑引起。

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()称为静态方法声明。这种方法遵循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;
        }      

}

这篇关于如何避免静电方面的参考,当我需要使用一个活动场景?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆