[英]Android: getString(R.string) in static method
When programming for Android sometimes you have to use static methods.在为 Android 编程时,有时您必须使用静态方法。 But when you try to access you resources in a static method with
getString(R.string.text)
you'll get an error.但是,当您尝试使用
getString(R.string.text)
以静态方法访问资源时,您将收到错误消息。 Making it static doesn't work.让它静态不起作用。
Does anyone knows a good way around this?有谁知道解决这个问题的好方法? The resource files in Android are very helpful for creating things in different languages or making changes to a text.
Android 中的资源文件对于创建不同语言的内容或更改文本非常有帮助。
一种或另一种方式,你需要一个 Context ......对于静态方法,这可能意味着你需要在调用它们时传递一个 Context 。
你可以使用Resources.getSystem().getStringArray(android.R.array.done);
This is how I access resources from inside static methods.这就是我从静态方法内部访问资源的方式。 Maybe not ideal, but.
也许不理想,但是。
First, I extend Application and set some public static field(s), and create a method to initialise them:首先,我扩展 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);
}
}
And in my manifest I register the extended Application:在我的清单中,我注册了扩展应用程序:
<application
android:name=".MyApp"/>
In my starter activity (MainActivity), I make a call to initialise the static resources:在我的启动活动 (MainActivity) 中,我调用初始化静态资源:
@Override
protected void onCreate(Bundle savedInstanceState) {
MyApp.initResources(this);
}
Then anywhere in your project, after MainActivity.onCreate(Bundle b) has run, you can call static methods that access your specified static resources:然后在你的项目中的任何地方,在 MainActivity.onCreate(Bundle b) 运行后,你可以调用访问你指定静态资源的静态方法:
public static void printAppName() {
Log.w("tag", "my app name: " + MyApp.APP_NAME);
}
Pass in a Context
(ie Activity
) instance as a parameter object to static method.将
Context
(即Activity
)实例作为参数对象传递给静态方法。 Then invoke getString
on the parameter.然后对参数调用
getString
。
The post below gives a tip for creating an Application
class to save your current context.下面的帖子提供了创建
Application
类以保存当前上下文的提示。 Your new Application
class will then be accessible from any other static method.然后可以从任何其他静态方法访问您的新
Application
类。
How can I get a resource content from a static context?
如何从静态上下文中获取资源内容?
One way is you can pass context to your static method.一种方法是您可以将上下文传递给静态方法。 check this out it definitely works
看看这个它绝对有效
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.