android如何在java类中使用字符串资源 [英] android how to use string resource in a java class
问题描述
在我的Java类中,我想使用来自strings.xml的字符串资源.
In my java class I want to use a string resource from strings.xml.
为此,我必须像下面这样使用
for that I have to use like below,
getString(R.string.address)
如果我的课堂是一项活动,则参加.但是我的班级是一个简单的Java类,该如何使用呢?
if my class is an activity then its taking. But my class is a simple java class , how can I use there?
有可能吗? 谢谢
推荐答案
一个类没有上下文,要使用字符串资源,需要一个上下文.因此,只需从活动中调用该类并提供一个参数context
,并在您的类构造函数中使用该上下文即可获取字符串资源.
A class does not have a context and to use a string resource a context is needed. So just call the class from an activity and give a parameter context
and within your class constructor just use that context to get the string resource.
在您的自定义类中,您需要为项目导入R名称空间以获取资源ID.
In your custom class you need to import the R namespace for the project to get the resource Id.
import com.myrandomapp.R;
然后获取实际的字符串
context.getString(R.string.COOL_STRING)
这篇关于android如何在java类中使用字符串资源的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!