How to avoid static context reference when I need to use a activity context?

青春壹個敷衍的年華 提交于 2019-12-24 15:06:20

问题


After read this topic avoiding memory leaks some doubts arouse.

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?

update-

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.


回答1:


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;
        }      

}



回答2:


That will crash your Application since Your Activity will be killed by OS when it runs out of Resources thus Context will also be null.. And its meaningless to give A background Activities Instance when you want to show pop up in the Foreground Activity.. What the Blog says is avoid passing activity.this where even getApplicationContext() can do the job..



来源:https://stackoverflow.com/questions/10010073/how-to-avoid-static-context-reference-when-i-need-to-use-a-activity-context

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!