Android:静态方法中的getString(R.string)

时间:2010-09-29 14:43:24

标签: android static getstring

为Android编程时,有时您必须使用静态方法。但是当您尝试使用getString(R.string.text)的静态方法访问资源时,您将收到错误消息。使其静止不起作用。

有谁知道这方面的好方法? Android中的资源文件对于创建不同语言的内容或更改文本非常有用。

6 个答案:

答案 0 :(得分:28)

不管怎样,你需要一个Context ...对于静态方法,这可能意味着你需要在调用它时传递Context。

答案 1 :(得分:17)

您可以使用Resources.getSystem().getStringArray(android.R.array.done);

答案 2 :(得分:7)

这是我从静态方法内部访问资源的方法。也许不理想,但是。

首先,我扩展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);
}

答案 3 :(得分:6)

Context(即Activity)实例作为参数对象传递给静态方法。然后在参数上调用getString

答案 4 :(得分:0)

以下帖子提供了创建Application类以保存当前上下文的提示。然后,您可以从任何其他静态方法访问新的Application类。

  

How can I get a resource content from a static context?

答案 5 :(得分:-2)

一种方法是可以将上下文传递给静态方法。 看看它确实有效

公共类听起来{

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);

}

}