![](/img/trans.png)
[英]Wrong return from R.string using Robotium .getString() method
[英]Android: getString(R.string) in static method
在为 Android 编程时,有时您必须使用静态方法。 但是,当您尝试使用getString(R.string.text)
以静态方法访问资源时,您将收到错误消息。 让它静态不起作用。
有谁知道解决这个问题的好方法? Android 中的资源文件对于创建不同语言的内容或更改文本非常有帮助。
一种或另一种方式,你需要一个 Context ......对于静态方法,这可能意味着你需要在调用它们时传递一个 Context 。
你可以使用Resources.getSystem().getStringArray(android.R.array.done);
这就是我从静态方法内部访问资源的方式。 也许不理想,但是。
首先,我扩展 Application 并设置一些公共静态字段,并创建一个方法来初始化它们:
public class MyApp extends Application {
// static resources
public static String APP_NAME;
public static void initResources(Context context) {
APP_NAME = context.getResources().getString(R.string.app_name);
}
}
在我的清单中,我注册了扩展应用程序:
<application
android:name=".MyApp"/>
在我的启动活动 (MainActivity) 中,我调用初始化静态资源:
@Override
protected void onCreate(Bundle savedInstanceState) {
MyApp.initResources(this);
}
然后在你的项目中的任何地方,在 MainActivity.onCreate(Bundle b) 运行后,你可以调用访问你指定静态资源的静态方法:
public static void printAppName() {
Log.w("tag", "my app name: " + MyApp.APP_NAME);
}
将Context
(即Activity
)实例作为参数对象传递给静态方法。 然后对参数调用getString
。
下面的帖子提供了创建Application
类以保存当前上下文的提示。 然后可以从任何其他静态方法访问您的新Application
类。
一种方法是您可以将上下文传递给静态方法。 看看这个它绝对有效
public class Sounds {
public static MediaPlayer getSoundTouch(Context context){
return MediaPlayer.create(context, R.raw.touch);
}
public static MediaPlayer getSoundLeak(Context context){
return MediaPlayer.create(context, R.raw.leak);
}
public static MediaPlayer getSoundFinish(Context context){
return MediaPlayer.create(context, R.raw.finish);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.