加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

java – Make Enum.toString()本地化

发布时间:2020-12-14 05:10:21 所属栏目:Java 来源:网络整理
导读:我正在开发一个 Android应用程序,我想知道我是否可以设置Enum.toString()多语言. 我将在Spinner上使用这个枚举,我想使用多语言文本. public class Types{ public enum Stature { tall (0,"tall"),average(1,"average"),small(2,"small"); private final int
我正在开发一个 Android应用程序,我想知道我是否可以设置Enum.toString()多语言.

我将在Spinner上使用这个枚举,我想使用多语言文本.

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

我不知道如何在Enum中使用Context.getString(),而且我已经硬编码为“高”,“平均”和“小”来测试它.我已经在帮助类中定义了这个枚举.

这样我如何使用微调框上的枚举:

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

你知道我该怎么办?

解决方法

假设这个资源路径
String resourceBundlePath = "my.package.bundles.messages"

在包裹my.package.bundles包可能有messages.properties,messages_en_US.properties等

然后,使用

ResourceBundle resourceBundle = ResourceBundle.getBundle(resourceBundlePath);
String messageKey = "myFirstMessage";
String message = resourceBundle.getMessage(messageKey);

message将包含message.properties上定义的messageKey属性的值.如果当前的区域设置实际上是en_US,您将从messages_en_US.properties获取值.如果当前的区域设置是您没有属性文件的值,则该值将来自默认的messages.properties

你也可以打电话

ResourceBundle.getBundle(resourceBundlePath,myLocale);

但是通常最好使用平台语言环境(看看jvm参数-Duser.language,-Duser.country)

您可以为每个要使用枚举元素名称翻译的枚举使用ResourceBundle,并在枚举的toString()实现中使用它:

@Override
public String toString() {
return resourceBudle.getString(super.toString());
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读