如果你开发的插件需要对多语言进行支持,就需要用到国际化功能。java
原生提供了ResourceBundle
类实现国际化功能,idea插件也可以通过国际化文件配置的方式,实现多语言支持。
# myPlugin_zh.properties
plugin.name=插件名称
#myPlugin_en.properties
plugin.name=Plugin Name
public class ResourceBundleUtil {
private static final ResourceBundleUtil INSTANCE = new ResourceBundleUtil();
private ResourceBundle resourceBundle;
private Locale currentLocale;
private ResourceBundleUtil() {
currentLocale = new Locale("en", "US");
String langSetting = "读取用户设置的语言";
if ("zh-CN".equals(langSetting) || ("Default".equals(langSetting)) {
currentLocale = new Locale("zh", "CN");
}
String bundleName = "messages.myPlugin";
resourceBundle = ResourceBundle.getBundle(bundleName, this.currentLocale);
}
public static String get(String key) {
return INSTANCE.getString(key);
}
public static String get(String key, Object... params) {
String message = INSTANCE.getString(key);
return String.format(message, params);
}
private String getString(String key) {
try {
return resourceBundle.getString(key);
} catch (Exception e) {
return "Key not found: " + key;
}
}
// 用户修改语言后,调用此方法
public static void setLocale(String langSetting) {
INSTANCE.currentLocale = new Locale("en", "US");
if ("zh-CN".equals(langSetting) || ("Default".equals(langSetting)) {
INSTANCE.currentLocale = new Locale("zh", "CN");
}
String bundleName = "messages.myPlugin";
INSTANCE.resourceBundle = ResourceBundle.getBundle(bundleName, INSTANCE.currentLocale);
}
}
除了提示语使用ResourceBundleUtil来获取对应的值外,插件中的菜单名也需要多语言支持,可以直接按照下面的格式,给注册的messageBundle properties文件添加配置后,可以自动获取对应语言的值。
action.<actionId>.text = Action Text
action.<actionId>.desc = Action Desc
示例:
plugin.xml中需要注册国际化文件
<idea-plugin>
<resource-bundle>messages.myPlugin</resource-bundle>
<actions>
<action id="MyPlugin.Action1" class="com.demo.Action1" />
</actions>
</idea-plugin>
国际化配置文件
# myPlugin_zh.properties
action.MyPlugin.Action1.text = 菜单1
action.MyPlugin.Action1.desc = 菜单1描述
#myPlugin_en.properties
action.MyPlugin.Action1.text = Action1 Name
action.MyPlugin.Action1.desc = Action1 Desc