Sap*_*Sun 236 java string android android-context android-resources
我发现R.string
将硬编码字符串保留在我的代码中非常棒,我想继续在一个实用程序类中使用它,该实用程序类与我的应用程序中的模型一起生成输出.例如,在这种情况下,我正在从活动之外的模型生成电子邮件.
是否可以在getString
外面使用Context
或Activity
?我想我可以通过当前的活动,但似乎没必要.如果我错了请纠正我!
编辑:我们可以不使用而访问资源Context
吗?
Gan*_*nus 405
您可以使用:
Resources.getSystem().getString(android.R.string.somecommonstuff)
Run Code Online (Sandbox Code Playgroud)
...在您的应用程序中的任何地方,甚至在静态常量声明中.不幸的是,它仅支持系统资源.
对于本地资源使用该解决方案.这不是微不足道的,但它确实有效.
Eri*_*ass 107
不幸的是,你可以访问任何字符串资源的唯一方法是使用Context
(即一个Activity
或Service
).在这种情况下我通常做的是简单地要求调用者传入上下文.
kon*_*mik 33
在MyApplication
,扩展Application
:
public static Resources resources;
Run Code Online (Sandbox Code Playgroud)
在MyApplication
's onCreate
:
resources = getResources();
Run Code Online (Sandbox Code Playgroud)
现在,您可以在应用程序的任何位置使用此字段.
Jan*_*icz 22
BTW,符号未找到错误的原因之一可能是您的IDE导入了android.R; 而不是你的一个.只需更改import android.R; 以进口your.namespace.R;
所以在不同的类中可以看到2个基本的东西:
//make sure you are importing the right R class
import your.namespace.R;
//don't forget about the context
public void some_method(Context context) {
context.getString(R.string.YOUR_STRING);
}
Run Code Online (Sandbox Code Playgroud)
Khe*_*raj 15
App.getRes().getString(R.string.some_id)
This will work everywhere in app. (Util class, Dialog, Fragment or any class in your app)
(1) Create or Edit (if already exist) your Application
class.
import android.app.Application;
import android.content.res.Resources;
public class App extends Application {
private static App mInstance;
private static Resources res;
@Override
public void onCreate() {
super.onCreate();
mInstance = this;
res = getResources();
}
public static App getInstance() {
return mInstance;
}
public static Resources getResourses() {
return res;
}
}
Run Code Online (Sandbox Code Playgroud)
(2) Add name field to your manifest.xml
<application
tag.
<application
android:name=".App"
...
>
...
</application>
Run Code Online (Sandbox Code Playgroud)
Now you are good to go. Use App.getRes().getString(R.string.some_id)
anywhere in app.
Khemraj 的回应中的最佳方法:
应用类
class App : Application() {
companion object {
lateinit var instance: Application
lateinit var resourses: Resources
}
// MARK: - Lifecycle
override fun onCreate() {
super.onCreate()
instance = this
resourses = resources
}
}
Run Code Online (Sandbox Code Playgroud)
清单中的声明
<application
android:name=".App"
...>
</application>
Run Code Online (Sandbox Code Playgroud)
常量类
class Localizations {
companion object {
val info = App.resourses.getString(R.string.info)
}
}
Run Code Online (Sandbox Code Playgroud)
使用
textView.text = Localizations.info
Run Code Online (Sandbox Code Playgroud)