【问题标题】:How to create multi language enum in Android?如何在 Android 中创建多语言枚举?
【发布时间】:2019-09-18 07:44:43
【问题描述】:

我正在使用这个枚举:

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;
    }
}

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

textView.setText(FruitType.getById(data.getFruitType()).getText())

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

【问题讨论】:

    标签: java android enums internationalization


    【解决方案1】:

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

    在您的情况下,最好FruitType 直接与字符串相关,而是与 res 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);
    
        ...
    }
    

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

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

    现在我们有了这个设置,只需根据您的目标语言环境进行通常的练习,即声明多个 strings.xml

    ../src/main/res
    ├── values
    │   └── strings.xml
    ├── values-in
    │   └── strings.xml
    ├── values-th
    │   └── strings.xml
    └── values-vi
        └── strings.xml
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-07-24
      • 1970-01-01
      • 2019-06-27
      • 2020-03-03
      相关资源
      最近更新 更多