Java 上下文或活动之外的 getString
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4253328/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
getString Outside of a Context or Activity
提问by SapphireSun
I've found the R.string
pretty awesome for keeping hardcoded strings out of my code, and I'd like to keep using it in a utility class that works with models in my application to generate output. For instance, in this case I am generating an email from a model outside of the activity.
我发现R.string
将硬编码字符串保留在我的代码之外非常棒,我想继续在一个实用程序类中使用它,该类与我的应用程序中的模型一起工作以生成输出。例如,在这种情况下,我从活动之外的模型生成电子邮件。
Is it possible to use getString
outside a Context
or Activity
? I suppose I could pass in the current activity, but it seems unnecessary. Please correct me if I'm wrong!
是否可以getString
在 aContext
或之外使用Activity
?我想我可以传入当前的活动,但这似乎没有必要。如果我错了,请纠正我!
Edit: Can we access the resources withoutusing Context
?
编辑:我们可以在不使用的情况下访问资源Context
吗?
采纳答案by Gangnus
Yes, we can access resources without using `Context`
是的,我们可以在不使用 `Context` 的情况下访问资源
You can use:
您可以使用:
Resources.getSystem().getString(android.R.string.somecommonstuff)
... everywhere in your application, even in static constants declarations. Unfortunately, it supports the system resources only.
...在您的应用程序中的任何地方,甚至在静态常量声明中。不幸的是,它只支持系统资源。
For local resources use this solution. It is not trivial, but it works.
对于本地资源,请使用此解决方案。这不是微不足道的,但它有效。
回答by Erich Douglass
Unfortunately, the only way you can access any of the string resources is with a Context
(i.e. an Activity
or Service
). What I've usually done in this case, is to simply require the caller to pass in the context.
不幸的是,您可以访问任何字符串资源的唯一方法是使用 a Context
(即 anActivity
或Service
)。在这种情况下,我通常所做的是简单地要求调用者传入上下文。
回答by Jan Naruszkiewicz
BTW, one of the reason of symbol not founderror may be that your IDE imported android.R; class instead of yours one. Just change import android.R;to import your.namespace.R;
顺便说一句,符号未找到错误的原因之一可能是您的IDE导入了android.R;班级而不是你的班级。只需更改import android.R; 以进口your.namespace.R;
So 2 basic things to get string visible in the different class:
因此,要使字符串在不同的类中可见,需要做 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);
}
回答by vivynz
I used
getContext().getApplicationContext().getString(R.string.nameOfString);
It works for me.
我用过getContext().getApplicationContext().getString(R.string.nameOfString);
它对我有用
。
回答by konmik
In MyApplication
, which extends Application
:
在 中MyApplication
,它扩展了Application
:
public static Resources resources;
In MyApplication
's onCreate
:
在MyApplication
的onCreate
:
resources = getResources();
Now you can use this field from anywhere in your application.
现在,您可以在应用程序的任何位置使用此字段。
回答by Versa
This should get you access to applicationContext
from anywhere allowing you to get applicationContext
anywhere that can use it; Toast
, getString()
, sharedPreferences
, etc.
这应该让您可以applicationContext
从任何地方访问,从而可以到达applicationContext
任何可以使用它的地方;Toast
,getString()
,sharedPreferences
,等。
The Singleton:
单身人士:
package com.domain.packagename;
import android.content.Context;
/**
* Created by Versa on 10.09.15.
*/
public class ApplicationContextSingleton {
private static PrefsContextSingleton mInstance;
private Context context;
public static ApplicationContextSingleton getInstance() {
if (mInstance == null) mInstance = getSync();
return mInstance;
}
private static synchronized ApplicationContextSingleton getSync() {
if (mInstance == null) mInstance = new PrefsContextSingleton();
return mInstance;
}
public void initialize(Context context) {
this.context = context;
}
public Context getApplicationContext() {
return context;
}
}
Initialize the Singleton in your Application
subclass:
在您的Application
子类中初始化单例:
package com.domain.packagename;
import android.app.Application;
/**
* Created by Versa on 25.08.15.
*/
public class mApplication extends Application {
@Override
public void onCreate() {
super.onCreate();
ApplicationContextSingleton.getInstance().initialize(this);
}
}
If I′m not wrong, this gives you a hook to applicationContext everywhere, call it with ApplicationContextSingleton.getInstance.getApplicationContext();
You shouldn′t need to clear this at any point, as when application closes, this goes with it anyway.
如果我没记错的话,这会给你一个到处都是 applicationContext 的钩子,调用它ApplicationContextSingleton.getInstance.getApplicationContext();
你不应该在任何时候清除它,因为当应用程序关闭时,它无论如何都会发生。
Remember to update AndroidManifest.xml
to use this Application
subclass:
请记住更新AndroidManifest.xml
以使用此Application
子类:
<?xml version="1.0" encoding="utf-8"?>
<manifest
xmlns:android="http://schemas.android.com/apk/res/android"
package="com.domain.packagename"
>
<application
android:allowBackup="true"
android:name=".mApplication" <!-- This is the important line -->
android:label="@string/app_name"
android:theme="@style/AppTheme"
android:icon="@drawable/app_icon"
>
Please let me know if you see anything wrong here, thank you. :)
如果您在这里看到任何错误,请告诉我,谢谢。:)
回答by Malus Jan
If you have a class that you use in an activity and you want to have access the ressource in that class, I recommend you to define a context as a private variable in class and initial it in constructor:
如果您有一个在活动中使用的类,并且想要访问该类中的资源,我建议您将上下文定义为类中的私有变量,并在构造函数中初始化它:
public class MyClass (){
private Context context;
public MyClass(Context context){
this.context=context;
}
public testResource(){
String s=context.getString(R.string.testString).toString();
}
}
Making an instant of class in your activity:
在您的活动中立即上课:
MyClass m=new MyClass(this);
回答by Khemraj
Unique Approach
独特的方法
App.getRes().getString(R.string.some_id)
App.getRes().getString(R.string.some_id)
This will work everywhere in app. (Util class, Dialog, Fragment or any class in your app)
这将适用于应用程序的任何地方。(Util 类、Dialog、Fragment 或您应用程序中的任何类)
(1) Create or Edit (if already exist) your Application
class.
(1) 创建或编辑(如果已经存在)您的Application
类。
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;
}
}
(2) Add name field to your manifest.xml
<application
tag.
(2) 将名称字段添加到您的manifest.xml
<application
标签中。
<application
android:name=".App"
...
>
...
</application>
Now you are good to go. Use App.getRes().getString(R.string.some_id)
anywhere in app.
现在你可以走了。App.getRes().getString(R.string.some_id)
在应用程序中的任何地方使用。
回答by Soham Chari
Here's what I did, In your MainActivity, create a static variable for context as shown below:
这是我所做的,在您的 MainActivity 中,为上下文创建一个静态变量,如下所示:
public static Context mContext;
and in the onCreate() initialise mContext to this;
并在 onCreate() 中将 mContext 初始化为此;
mContext = this;
Then, in the file where you want to access context, say,
然后,在您要访问上下文的文件中,例如,
private Context context = MainActivity.mContext;
Now, you can get a string resource in the following manner,
现在,您可以通过以下方式获取字符串资源,
String myString = context.getResources().getString(R.string.resource_id);
回答by Mickael Belhassen
The best approach from the response of Khemraj:
来自 Khemraj 回应的最佳方法:
App class
应用类
class App : Application() {
companion object {
lateinit var instance: Application
lateinit var resourses: Resources
}
// MARK: - Lifecycle
override fun onCreate() {
super.onCreate()
instance = this
resourses = resources
}
}
Declaration in the manifest
清单中的声明
<application
android:name=".App"
...>
</application>
Constants class
常量类
class Localizations {
companion object {
val info = App.resourses.getString(R.string.info)
}
}
Using
使用
textView.text = Localizations.info