Android:包含可以转换为其他区域设置的值的枚举

时间:2016-07-28 21:50:54

标签: android enums internationalization locale

假设我低于static getters

enum

当我调用它public enum Feelings { happy("label1"),sad("label2") private final String name; private Feelings(String s) { name = s; } public boolean equalsName(String otherName) { return (otherName == null) ? false : name.equals(otherName); } public String toString() { return name; } } 时,它返回为不同枚举定义的标签。我在UI上使用这些标签,它们将显示给用户。

当我考虑使用不同的语言环境发布我的应用程序时,我想到如何定义这些标签以便将它们翻译成其他语言?

2 个答案:

答案 0 :(得分:1)

与在枚举之外处理本地化的方式不应有太大的不同。只需要传递参考资源。如下所示:

public enum Feelings {
    happy(R.string.happy),
    sad(R.string.sad)

    private final int nameId;

    private Feelings(int nameId) {
        this.nameId = nameId;
    }

    public String toString(Resources res) {
        return res.getString(nameId);
    }
}

答案 1 :(得分:0)

您可以使用字符串资源ID。

,而不是在枚举中设置标签的实际值
public enum Feelings {
  happy(R.string.happy_label), sad(R.string.sad_label);
  private final int strId;

  private Feelings(int strId) {
    this.strId = strId;
  }

  @StringRes public int getStringId() {
    return strId;
  }
}

这样,Android会根据设备的区域设置选择正确的字符串翻译

您的使用情况可能如下所示:

textView.setText(Feelings.happy.getStringId());