在非活动类中获取上下文 [英] get Context in non-Activity class

查看:36
本文介绍了在非活动类中获取上下文的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在android应用程序中,如果活动类名称已知,有没有办法在非活动类中获取android中的上下文?

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?

推荐答案

如果你的类是非活动类,并从活动中创建它的实例,你可以通过后者的构造函数传递上下文的实例,如下所示:

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

这篇关于在非活动类中获取上下文的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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