在我的java类中,我想使用strings.xml中的字符串资源。
为此我必须使用如下,
getString(R.string.address)
如果我的课程是一项活动,那么它就开始了。但是我的类是一个简单的java类,我怎么能在那里使用?
有可能吗? 谢谢
答案 0 :(得分:37)
类没有上下文,并且使用字符串资源需要上下文。因此,只需从活动中调用该类并提供参数context
,并在类构造函数中使用该上下文来获取字符串资源。
在自定义类中,您需要为项目导入R命名空间以获取资源ID。
import com.myrandomapp.R;
然后获取实际的字符串
context.getString(R.string.COOL_STRING)
答案 1 :(得分:16)
您可以将Activity类的上下文传递给java类并访问资源。
来自您的活动类
Helper helper = new Helper(this);
您的Java类
public class Helper {
Helper(Context c){
c.getString(R.string.address);
}
}
答案 2 :(得分:10)
您可以在自定义Application Context
类
Application
public class App extends Application{
private static Context mContext;
@Override
public void onCreate() {
super.onCreate();
mContext = getApplicationContext();
}
public static Context getContext(){
return mContext;
}
}
然后你只需要调用App.getContext().getResources()
来获取任何资源值。
请记住,此Context
是Application
类型,因此有些内容Context
不适合使用。请阅读this了解更多信息。
答案 3 :(得分:-1)
如果你添加这一行就可以完成:
// this is the object itself, and idString is the ID String bound to the literal.
this.getString(R.string.idString)
我希望这条评论可以帮到你!
BRS。