fortyCakes fortyCakes - 5 months ago 28
Android Question

How to access resource strings from enum's ToString in Android?

In my app, I have a Spinner being filled from an enum:

ArrayAdapter<myEnum> enumAdapter = new ArrayAdapter<Stroke> (parentActivity.getApplicationContext(), R.layout.simple_spinner_item, myEnum.values());

This uses an override of the enum's
method to get a friendly name for the enum values to display in the
. Currently my enum has strings hardcoded for the friendly names but I'd like to move these to
to support localization.

However, toString doesn't have access to a
so I'm not sure how to resolve the resource ids.

Is there any way of getting localised strings in the toString() method of an enum?


If I understand this correctly, the real question here is how to get a Context from your enum, so that you can call Context.getString() to get localized versions of the Strings you need.

One approach, would be to set a static member variable of type Context in your application's onCreate() method, which is described in this answer. The idea here is that every time your application gets created or recreated, you'll hold on to the application context in a variable that's easy to get to.

Then, pass in the resource ID in the constructor of your enum values, and use the Context in your toString() method.

For example:

public enum Example {

    private int mResourceId;

    private Example(int id) {
        mResourceId = id;

    public String toString() {
        return App.getContext().getString(mResourceId);