1. 程式人生 > >Android 漢字首字母排序

Android 漢字首字母排序

需要用到的方法:

用到jar包: pinYin4j.jar

 /** 
     * 漢字轉換位漢語拼音首字母,英文字元不變 
     * @param chines 漢字 
     * @return 拼音 
     */  
     public static String converterToFirstSpell(String chines){         
         String pinyinName = "";  
         char[] nameChar = chines.toCharArray();  
         HanyuPinyinOutputFormat defaultFormat = new HanyuPinyinOutputFormat();  
         defaultFormat.setCaseType(HanyuPinyinCaseType.LOWERCASE);  
         defaultFormat.setToneType(HanyuPinyinToneType.WITHOUT_TONE);  
         for (int i = 0; i < nameChar.length; i++) {  
             if (nameChar[i] > 128) {  
                 try {  
                     pinyinName += PinyinHelper.toHanyuPinyinStringArray(nameChar[i], defaultFormat)[0].charAt(0);  
                 } catch (BadHanyuPinyinOutputFormatCombination e) {  
                     e.printStackTrace();  
                 }  
             }else{  
                 pinyinName += nameChar[i];  
             }  
         }  
         return pinyinName;  
     }  

排序方法:
  // 漢字排序

        Collections.sort(contactList, new Comparator<User>() {

            @Override
            public int compare(User lhs, User rhs) {
                String s1=converterToFirstSpell(lhs.getNick());
                String s2=converterToFirstSpell(rhs.getNick());
                return Collator.getInstance(Locale.ENGLISH).compare(s1, s2); 
//                return lhs.getNick().compareTo(rhs.getNick());
                
            }
        });