在我的 Java 类中,我想使用 strings.xml 中的字符串资源。
为此我想使用这样的东西:
getString(R.string.address)
如果我的课是一项活动,那么它就是有效的。
但是,如果我的类是一个简单的 Java 类,我该如何使用它呢?
类没有上下文,要使用字符串资源需要上下文。因此,只需从活动中调用该类并提供一个参数
context
,然后在您的类构造函数中只需使用该上下文即可获取字符串资源。
在您的自定义类中,您需要为项目导入 R 命名空间以获取资源 Id。
import com.myrandomapp.R;
然后得到实际的字符串
context.getString(R.string.COOL_STRING)
可以将Activity类的上下文传递给java类,访问资源。
来自您的活动课
Helper helper = new Helper(this);
你的 Java 类
public class Helper {
Helper(Context c){
c.getString(R.string.address);
}
}
您可以在自定义
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了解更多信息。
如果你添加这一行就可以完成:
// this is the object itself, and idString is the ID String bound to the literal.
this.getString(R.string.idString)
希望这篇评论对你有帮助!
兄弟