简体   繁体   中英

Android: getString(R.string) in static method

When programming for Android sometimes you have to use static methods. But when you try to access you resources in a static method with getString(R.string.text) you'll get an error. 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.

一种或另一种方式,你需要一个 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:

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:

@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:

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. Then invoke getString on the parameter.

The post below gives a tip for creating an Application class to save your current context. Your new Application class will then be accessible from any other static method.

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

    }

 }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM