Android Studio 插件:unicode 转 中文
背景
项目中遇到这样的文件,里面中文名称用 unicode 来表示,看起来不方便,于是做了一个插件,方便查看中文。
效果
实现
public class UnicodeToCn extends AnAction {
@Override
public void actionPerformed(AnActionEvent e) {
// 获取编辑器model
final Editor mEditor = e.getData(PlatformDataKeys.EDITOR);
final Project project = e.getProject();
if (null == mEditor || project == null) {
return;
}
// 获取选中区域model
final SelectionModel selectionModel = mEditor.getSelectionModel();
selectionModel.selectLineAtCaret();
String selectedText = selectionModel.getSelectedText();
selectionModel.removeSelection();
System.out.println(selectedText);
if (selectedText == null || selectedText.equals("")) {
System.out.println("selectedText is null");
return;
}
Pattern p = Pattern.compile("((\\\\u|\\\\\\\\u)(\\p{XDigit}){4})+");
Matcher m = p.matcher(selectedText);//获取 matcher 对象
if (!m.find()) {
System.out.println("no unicode");
return;
}
selectedText = m.group(0);
System.out.println(selectedText);
String chinese = Util.unicodeToCn(selectedText);
System.out.println(chinese);
showPopupBalloon(mEditor, chinese);
}
private void showPopupBalloon(final Editor editor, final String result) {
ApplicationManager.getApplication().invokeLater(new Runnable() {
public void run() {
System.out.println("6");
JBPopupFactory factory = JBPopupFactory.getInstance();
factory.createHtmlTextBalloonBuilder(result, null,
new JBColor(new Color(186, 238, 186), new Color(73, 117, 73)), null)
.setFadeoutTime(5000)
.createBalloon()
.show(factory.guessBestPopupLocation(editor), Balloon.Position.below);
}
});
}
}
public class Util {
public static String unicodeToCn(String unicode) {
// 有两种转义,一个是 java 字符串中的转义,一个是 regex 中的转义
// "\\u" 字面值,java 字符串转义为 "\\\\u",regex 转义为 "\\\\\\\\u"
// "\ u" 字面值,java 字符串转义为 "\\u",regex 转义为 "\\\\u"
// 上一行中的 "\ u",加一个空格是因为不加的话,在 java doc 的编译过程中会识别 unicode,报非法的 Unicode 转义
String[] strs;
if (unicode.contains("\\\\u")) {
strs = unicode.split("\\\\\\\\u");
} else {
strs = unicode.split("\\\\u");
}
StringBuilder returnStr = new StringBuilder();
// 由于unicode字符串以 "\\u" 或 "\ u" 开头,因此分割出的第一个字符是""。
try {
for (int i = 1; i < strs.length; i++) {
returnStr.append((char) Integer.valueOf(strs[i], 16)
.intValue());
}
} catch (NumberFormatException e) {
e.printStackTrace();
}
return returnStr.toString();
}
}
写插件时的注意点:
- 运行时弹出的那个 idea 的 log 要在编写的那个 idea 的 console 中看。
- 遇到修改无效的情况,可以修改 plugin.xml 的 version 看看。