使 Enum.toString() 本地化 [英] Make Enum.toString() localized
问题描述
我正在开发一个 Android 应用程序,我想知道我是否可以设置 Enum.toString()
多语言.
I'm developing an Android application and I want to know if I can set Enum.toString()
multilanguage.
我将在 Spinner
上使用这个 Enum
并且我想使用多语言文本.
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; }
}
}
我不知道如何在 Enum 中使用 Context.getString()
,我已经硬编码了高"、平均"和小"来测试它.我已经在帮助类中定义了 enum
.
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.
这是我在 Spinner
上使用 enum
的方式:
This how I use the enum
on a Spinner
:
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
等
In package my.package.bundles
you may have messages.properties
, messages_en_US.properties
etc.
然后,使用
ResourceBundle resourceBundle = ResourceBundle.getBundle(resourceBundlePath);
String messageKey = "myFirstMessage";
String message = resourceBundle.getMessage(messageKey);
message
将包含在 messages.properties
上定义的 messageKey
属性的值.如果当前的 Locale 实际上是 en_US
,您将从 messages_en_US.properties
获取值.如果当前语言环境是您没有的属性文件,则该值将来自默认的 messages.properties
message
will contain the value of the messageKey
property defined on messages.properties
. If the current Locale is actually en_US
you will get the value from messages_en_US.properties
. If the current locale is something you do not have a properties file for the value will be from the default messages.properties
你也可以打电话
ResourceBundle.getBundle(resourceBundlePath, myLocale);
但通常最好使用平台语言环境(查看 jvm 参数 -Duser.language, -Duser.country)
but it is generally better to use the platform locale (have a look at jvm arguments -Duser.language, -Duser.country)
您可以为每个要翻译的枚举使用一个 ResourceBundle,键是枚举元素名称,并在枚举的 toString() 实现中使用它:
You can have a ResourceBundle for each enum you want to translate with keys the enum element names and use it in the toString() implementation of your enum:
@Override
public String toString() {
return resourceBudle.getString(super.toString());
}
这篇关于使 Enum.toString() 本地化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!