get Context in non-Activity class [duplicate]

冷暖自知 提交于 2019-11-26 05:26:07

问题


In an android Application, is there any way to get the context in android in a non-activity class if the activity class name is known?


回答1:


If your class is non-activity class, and creating an instance of it from the activiy, you can pass an instance of context via constructor of the later as follows:

class YourNonActivityClass{

// variable to hold context
private Context context;

//save the context recievied via constructor in a local variable

public YourNonActivityClass(Context context){
    this.context=context;
}

}

You can create instance of this class from the activity as follows:

new YourNonActivityClass(this);


来源:https://stackoverflow.com/questions/17917968/get-context-in-non-activity-class

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