我发现R.string非常棒,可以将硬编码的字符串排除在代码之外,我希望在与应用程序中的模型一起工作的实用程序类中继续使用它来生成输出。例如,在本例中,我从活动外部的模型生成了一封电子邮件。
是否可以在上下文或活动之外使用getString ?我想我可以通过目前的活动,但似乎没有必要。如果我说错了,请指正!
编辑:我们可以在不使用上下文的情况下访问资源吗?
我发现R.string非常棒,可以将硬编码的字符串排除在代码之外,我希望在与应用程序中的模型一起工作的实用程序类中继续使用它来生成输出。例如,在本例中,我从活动外部的模型生成了一封电子邮件。
是否可以在上下文或活动之外使用getString ?我想我可以通过目前的活动,但似乎没有必要。如果我说错了,请指正!
编辑:我们可以在不使用上下文的情况下访问资源吗?
当前回答
在MyApplication中,扩展Application:
public static Resources resources;
在MyApplication的onCreate中:
resources = getResources();
现在您可以在应用程序中的任何地方使用该字段。
其他回答
我使用 getContext () .getApplicationContext () .getString (R.string.nameOfString); 这对我很管用。
是的,我们可以不使用“上下文”来访问资源
你可以使用:
Resources.getSystem().getString(android.R.string.somecommonstuff)
... 在应用程序的任何地方,甚至在静态常量声明中。 不幸的是,它只支持系统资源。
对于本地资源,请使用此解决方案。这不是小事,但很有效。
从赫姆拉吉的回应来看,最好的方法是:
应用程序类
class App : Application() {
companion object {
lateinit var instance: Application
lateinit var resourses: Resources
}
// MARK: - Lifecycle
override fun onCreate() {
super.onCreate()
instance = this
resourses = resources
}
}
舱单上的声明
<application
android:name=".App"
...>
</application>
常量类
class Localizations {
companion object {
val info = App.resourses.getString(R.string.info)
}
}
使用
textView.text = Localizations.info
以下是基于Khemraj Sharma的回答,这是Kotlin版本,有一个额外的扩展作为奖励:
class App: Application() {
override fun onCreate() {
super.onCreate()
mInstance = this
res = resources
}
companion object{
private var mInstance: App? = null
private var res: Resources? = null
fun getInstance(): App? {
return mInstance
}
fun getRes(): Resources? {
return res
}
}
}
然后我们可以创建一个扩展:
fun Int.resourceToString(): String {
return App.getRes()?.getString(this) ?: "Not Found"
}
并直接在任何资源id上使用扩展:
var asString = R.string.my_string.resourceToString()
如果你有一个在活动中使用的类,并且你想要访问该类中的资源,我建议你在类中定义一个context作为私有变量,并在构造函数中初始化它:
public class MyClass (){
private Context context;
public MyClass(Context context){
this.context=context;
}
public testResource(){
String s=context.getString(R.string.testString).toString();
}
}
在你的活动中展现一流的一面:
MyClass m=new MyClass(this);