6

Is there a sensible, clean way to refer to application resources from static initalizer code in my android classes.

I would specifically like to define an enum which contains the values of some resource strings in its constants.

Here is some pseudo code for the enum

private enum MyEnum {
    Const1(getString(R.string.string1)),
    Const2(getString(R.string.string2)),
    Const3(getString(R.string.string3));

    private String strVal;

    MyEnum(String strVal){
        this.strVal = strVal;
    }
}

This question applies to any kind of static initialization.

fleetway76
  • 1,600
  • 9
  • 12
  • I am coming round to the idea that the only elegant solution is to simply store the numeric IDs of the string resources and have the client of the enum do the lookup. Or have a getter for the string value that takes a context and does the lookup. Any other suggestions? – fleetway76 Jun 14 '11 at 21:20

1 Answers1

11

I don't think there is a direct way as context is required to load resources. However, what you could do is to provide a method in your enum to get required string once context is available. Something like

private enum MyEnum {
    Const1(R.string.string1),
    Const2(R.string.string2),
    Const3(R.string.string3);

    private int resId;

    MyEnum(int resId){
        this.resId = resId;
    }

    public String resource(Context ctx) {
       return ctx.getString(resId);
    }
}

So you access it like

String val = Const3.resource(context);
Alex Gitelman
  • 24,429
  • 7
  • 52
  • 49