I have a problem re. an Android application's resources:
My application has misc. modes (edit/plan/exec), which I would like to describe using an enumeration type. I would, however, like to populate the enumeration-values with strings that stem from the resource string.xml file, i.e. instead of
enum Mode {
EDIT ("edit"),
PLAN ("plan"),
EXEC ("exec");
String name;
Mode(String name) { this.name = name; }
@Override
public String toString() { return this.name; }
};
I would like to write something like:
enum Mode {
EDIT (getResources().getText(R.string.mode_edit).toString()),
PLAN (getResources().getText(R.string.mode_plan).toString())),
EXEC (getResources().getText(R.string.mode_exec).toString()));
String name;
Mode(String name) { this.name = name; }
@Override
public String toString() { return this.name; }
}
which would e.g. allow to modify the modes' names using the resource file and thus allow for later name modifications without code changes, internationalization, etc.
The problem is, that the standard access to the resources is via an Activity's getResources()-method which is only available in the constructor (and during instance methods). The enumeration declaration, however, is part of a class' static initialization code. Is there any way to access an app's resources in a static way?
Michael
Alternatively you can do following:
In your
Application.onCreate()
orActivity.onCreate()
:and in your
enum Mode
:Based on this https://stackoverflow.com/a/3560656/262462 and because R.string contains integers
Thanks, radek-k, for the examples! In the meantime I came up myself with a somewhat similar idea, namely I added a static method to the enum to which I then pass the resource-handle during the Activity's onCreate()-method. That allows the toString()-method then to access the resource strings. IMHO not very elegant, but it works...
Cheers, Michael