如何在Android中创建多语言枚举?

Coo*_*ter 1 java enums android internationalization

我正在使用这个枚举:

public enum FruitType{
    APPLE("1", "Apple"),
    ORANGE("2", "Orange"),
    BANANA("3", "Banana"),
    UNKNOWN("0", "UNKNOWN");

    private static final Map<String, FruitType> lookup
            = new HashMap<String, FruitType>();

    static {
        for ( FruitType s : EnumSet.allOf(FruitType.class) )
            lookup.put(s.getCode(), s);
    }

    public static FruitType getById(String id) {
        for(FruitType e : values()) {
            if(e.Code.equals(id)) return e;
        }
        return UNKNOWN;
    }

    private String Code;
    private String Text;

    FruitType( String Code, String Text ) {
        this.Code = Code;
        this.Text = Text;
    }

    public final String getCode() {
        return Code;
    }

    public final String getText() {
        return Text;
    }
}
Run Code Online (Sandbox Code Playgroud)

我从服务器获取数字(0-3),并且我想使用本地化的字符串来使用枚举的getText()方法。

textView.setText(FruitType.getById(data.getFruitType()).getText())
Run Code Online (Sandbox Code Playgroud)

如何在枚举的“文本”中使用字符串资源而不是静态文本?

MrH*_*rio 6

Android已经为您提供了一种非常可靠的方法来通过其资源目录结构解决i18n。

在你的情况下,它可能会更好不是FruitType直接关系到一个字符串,而是一个资源ID:

public enum FruitType {

    APPLE("1", R.string.apple),
    ORANGE("2", R.string.orange),
    BANANA("3", R.string.banana),
    UNKNOWN("0", R.string.unknown_fruit);

    ...
}
Run Code Online (Sandbox Code Playgroud)

然后,您可以定义一种便捷方法来获取这些枚举的实际字符串值,如下所示:

public enum FruitType {

    ...

    public final String getText(Context context) {
       return context.getString(this.Text)
    }

    ...
}
Run Code Online (Sandbox Code Playgroud)

现在我们有了这个设置,只需继续strings.xml按照目标区域设置声明多个的常规练习即可:

../src/main/res
??? values
?   ??? strings.xml
??? values-in
?   ??? strings.xml
??? values-th
?   ??? strings.xml
??? values-vi
    ??? strings.xml
Run Code Online (Sandbox Code Playgroud)