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

Sar*_*den 27 static android getstring

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

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

ben*_*nvd 29

无论如何,你需要一个上下文......对于静态方法,这可能意味着你需要在调用它时传递一个Context.


小智 18

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

  • 这是一个很好的解决方案,唯一的缺点是你只能使用系统资源. (2认同)

BAR*_*ARJ 8

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

首先,我扩展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);
  }
}
Run Code Online (Sandbox Code Playgroud)

在我的清单中,我注册了扩展的应用程序:

<application 
  android:name=".MyApp"/>
Run Code Online (Sandbox Code Playgroud)

在我的启动活动(MainActivity)中,我调用初始化静态资源:

@Override
protected void onCreate(Bundle savedInstanceState) {
  MyApp.initResources(this);   
}
Run Code Online (Sandbox Code Playgroud)

然后在项目的任何地方,在运行MainActivity.onCreate(Bundle b)之后,您可以调用访问指定静态资源的静态方法:

public static void printAppName() {
  Log.w("tag", "my app name: " + MyApp.APP_NAME);
}
Run Code Online (Sandbox Code Playgroud)


Kon*_*rov 6

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

  • 是什么让你认为我建议存储一个Context参考? (7认同)
  • ^错了.getApplicationContext()将无法在静态方法中使用. (3认同)