Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I'm developing an Android application and I want to know if I can set Enum.toString() multilanguage.

I'm going to use this Enum on a Spinner and I want to use multi language texts.

public class Types
{
    public enum Stature
    {
        tall (0, "tall"),
        average(1, "average"),
        small(2, "small");

        private final int stature;
        private final String statureString;

        Stature(int anStature, String anStatureString) { stature = anStature; statureString = anStatureString; }

        public int getValue() { return stature; }

        @Override
        public String toString() { return statureString; }
    }
}

I don't know how to use Context.getString() inside an Enum, and I have hardcoded "tall", "average" and "small" to test it. I have defined that enum inside on a helper class.

This how I use the enum on a Spinner:

mSpinStature.setAdapter(new ArrayAdapter<Stature>(mActivity, android.R.layout.simple_dropdown_item_1line, Stature.values()));

Do you know how can I do it?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
288 views
Welcome To Ask or Share your Answers For Others

1 Answer

I created a simple library which is a part of my big project (Xdroid):

compile 'com.shamanland:xdroid-enum-format:0.2.4'

Now you can avoid the same monkey-job (declaring field, constructor, etc) for all enumetations by using annotations:

public enum State {
    @EnumString(R.string.state_idle)
    IDLE,

    @EnumString(R.string.state_pending)
    PENDING,

    @EnumString(R.string.state_in_progress)
    IN_PROGRESS,

    @EnumString(R.string.state_cancelled)
    CANCELLED,

    @EnumString(R.string.state_done)
    DONE;
}

And then use the common Java approach - use extensions of class java.text.Format:

public void onStateChanged(State state) {
    EnumFormat enumFormat = EnumFormat.getInstance();
    toast(enumFormat.format(state));
}

strings.xml

<string name="state_idle">Idle</string>
<string name="state_pending">Pending</string>
<string name="state_in_progress">In progress</string>
<string name="state_cancelled">Cancelled</string>
<string name="state_done">Done</string>

Look here how to show Toast simply.

You can also compile a demo app from github.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...