​​Android 汉字转拼音的多种实现方式​​

主要使用以下几种方式:
1.TinyPinyin开源库:https://github.com/promeG/TinyPinyin(推荐)
2.jpinyin开源库:https://github.com/stuxuhai/jpinyin
3.pinyin4j开源库:http://pinyin4j.sourceforge.net/
4.使用拼音字符和ASCII码的映射关系:很多博客代码在这种方式的实现上转换过程可能不对(实测)

以下是TinyPinyin的使用方式:
引入库

//拼音中文转换
implementation 'com.github.promeg:tinypinyin:2.0.3' // TinyPinyin核心包,约80KB
implementation 'com.github.promeg:tinypinyin-lexicons-android-cncity:2.0.3' // 可选,适用于Android的中国地区词典
implementation 'com.github.promeg:tinypinyin-lexicons-java-cncity:2.0.3' // 可选,适用于Java的中国地区词典

中文转拼音

public class PinyinUtil {

/**
* 中文转换成拼音,返回结果是list
*
* @param source 原始字符
* @return 中国->["ZHONG", "GUO"] 大写
*/
public static List<String> getPinYinList(String source) {
if (source == null || source.isEmpty()) {
return null;
}
List<String> pinyinList = new ArrayList<>();
try {
String str = Pinyin.toPinyin(source,"|");
String[] arr = str.split("\\|");
return Arrays.asList(arr);
}
catch (Exception e){
e.printStackTrace();
}

return pinyinList;
}

}