android 漢字轉拼音


http://www.cnblogs.com/XiaoXiaoCoder/archive/2012/03/27/2420438.html
 

在Java中顯示漢字拼音。

以Android為例,首先我們需要導入一個外部jar包,也就是將獲得漢字拼音的工具包。通過調用jar包中提供的方法即可獲得漢字的拼音了。

 

 

寫一個工具類,初始化jar包中的HanyuPinyinOutputFormat類,在對該對象進行一下設置,具體設置有什么用就不詳細說明了。 最后的文件下載后里面有相關的api文檔。之后只需要調用PinyinHelper.toHanyuPinyinStringArray(hanzi, hanyuPinyin);方法,將漢字和剛才初始化的漢語拼音輸出格式對象以參數的形式傳入就可以獲得該漢字的拼音了。

漢字轉拼音工具類:

 

?
public class HanZiToPinYin {
     /**
      * 返回一個字的拼音
      * @param hanzi
      * @return
      */
     public static String toPinYin( char hanzi){
         HanyuPinyinOutputFormat hanyuPinyin = new HanyuPinyinOutputFormat();
         hanyuPinyin.setCaseType(HanyuPinyinCaseType.LOWERCASE);
         hanyuPinyin.setToneType(HanyuPinyinToneType.WITH_TONE_MARK);
         hanyuPinyin.setVCharType(HanyuPinyinVCharType.WITH_U_UNICODE);
         String[] pinyinArray= null ;
         try {
             //是否在漢字范圍內
             if (hanzi>= 0x4e00 && hanzi<= 0x9fa5 ){
                 pinyinArray = PinyinHelper.toHanyuPinyinStringArray(hanzi, hanyuPinyin);
             }
         } catch (BadHanyuPinyinOutputFormatCombination e) {
             e.printStackTrace();
         }
         //將獲取到的拼音返回
         return pinyinArray[ 0 ];
     }
}

  

Android中調用代碼如下:
?
public class TestActivity extends Activity {
     /** Called when the activity is first created. */
     TextView tView;
     @Override
     public void onCreate(Bundle savedInstanceState) {
         super .onCreate(savedInstanceState);
         tView= new TextView( this );
         tView.setTextSize( 24 );
         tView.setTextColor(Color.WHITE);
         String hanziString= "你" ;
         String pinyinString= HanZiToPinYin.toPinYin(hanziString.charAt( 0 ));
         tView.setText( "拼音:" +pinyinString+ "\n" + "漢字:" +hanziString);
         setContentView(tView);
     }
}

  

顯示結果如下:

 
 
漢字轉拼音的工具包的下載地址: http://download.csdn.net/detail/liuzg129/4178303


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM