I\'m developing an Android application and I want to know if I can set Enum.toString()
multilanguage.
I\'m going to use this Enum
on a
@Override
public String toString()
{
//java
return ResourceBundle.getBundle().getString(id);
//android?
App.getContext().getString(id);
}
I would leave enum as is and use the standard ResourceBundle approach http://docs.oracle.com/javase/tutorial/i18n/resbundle/concept.html using Enum.toString as the key
I created a simple library which is a part of my big project (Xdroid):
compile 'com.shamanland:xdroid-enum-format:0.2.4'
Now you can avoid the same monkey-job (declaring field, constructor, etc) for all enumetations by using annotations:
public enum State {
@EnumString(R.string.state_idle)
IDLE,
@EnumString(R.string.state_pending)
PENDING,
@EnumString(R.string.state_in_progress)
IN_PROGRESS,
@EnumString(R.string.state_cancelled)
CANCELLED,
@EnumString(R.string.state_done)
DONE;
}
And then use the common Java approach - use extensions of class java.text.Format
:
public void onStateChanged(State state) {
EnumFormat enumFormat = EnumFormat.getInstance();
toast(enumFormat.format(state));
}
strings.xml
<string name="state_idle">Idle</string>
<string name="state_pending">Pending</string>
<string name="state_in_progress">In progress</string>
<string name="state_cancelled">Cancelled</string>
<string name="state_done">Done</string>
Look here how to show Toast
simply.
You can also compile a demo app from github.
Assume this resource path
String resourceBundlePath = "my.package.bundles.messages"
In package my.package.bundles
you may have messages.properties
, messages_en_US.properties
etc.
Then, using
ResourceBundle resourceBundle = ResourceBundle.getBundle(resourceBundlePath);
String messageKey = "myFirstMessage";
String message = resourceBundle.getMessage(messageKey);
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
You can also call
ResourceBundle.getBundle(resourceBundlePath, myLocale);
but it is generally better to use the platform locale (have a look at jvm arguments -Duser.language, -Duser.country)
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());
}