MainActivity如下:
package cn.cc; import android.app.Activity; import android.os.Bundle; /** * Demo描述: * 利用pinyin4j将汉字转换为拼音 * * 注意事项: * 添加pinyin4j.jar包 */ public class MainActivity extends Activity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); init(); } private void init(){ String fixedString1=PinyinUtills.pinYinOf("大白菜"); String fixedString2=PinyinUtills.pinYinOf("9527大白菜"); String fixedString3=PinyinUtills.pinYinOf("绿豆芽"); System.out.println("fixedString1="+fixedString1+",fixedString2="+fixedString2+",fixedString3="+fixedString3); } }
PinyinUtills如下:
package cn.cc; import net.sourceforge.pinyin4j.PinyinHelper; import net.sourceforge.pinyin4j.format.HanyuPinyinCaseType; import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat; import net.sourceforge.pinyin4j.format.HanyuPinyinToneType; import net.sourceforge.pinyin4j.format.HanyuPinyinVCharType; import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination; public class PinyinUtills { public static String pinYinOf(String hanziString) { StringBuilder stringBuilder = new StringBuilder(); String tempString; if (null != hanziString) { for (int i = 0; i < hanziString.length(); i++) { tempString = getPinYinOfChar(hanziString.charAt(i)); stringBuilder.append(tempString); } } return stringBuilder.toString(); } private static String getPinYinOfChar(char hanziChar) { String[] stringArray = null; HanyuPinyinOutputFormat format = new HanyuPinyinOutputFormat(); format.setToneType(HanyuPinyinToneType.WITHOUT_TONE); format.setCaseType(HanyuPinyinCaseType.LOWERCASE); // 处理拼音里面的u和v format.setVCharType(HanyuPinyinVCharType.WITH_V); try { stringArray = PinyinHelper.toHanyuPinyinStringArray(hanziChar, format); } catch (BadHanyuPinyinOutputFormatCombination e) { e.printStackTrace(); } if (null != stringArray) { return stringArray[0]; } else { return ""; } } }
main.xml如下:
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" > <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerInParent="true" android:text="利用pinyin4j将汉字转换为拼音" /> </RelativeLayout>