您的当前位置:首页正文

Android 按照字母排序汉字,可用于通讯录

2024-11-20 来源:个人技术集锦

比较类,资源类

public class CompareData implements Comparable<CompareData> {

    private String str;

    public CompareData(String str) {
        this.str = str;
    }

    @Override
    public int compareTo(CompareData o) {

        char strFirstChar = getStrFirstChar(str);
        char strFirstCharO = getStrFirstChar(o.str);
        if (strFirstChar < strFirstCharO) {
            return -1;
        }
        if (strFirstChar > strFirstCharO) {
            return 1;
        }
        return 0;
    }

    private char getStrFirstChar(String str) {
        String pinyinFirstLetter = PinyinUtils.getPinyinFirstLetter(str);
        char c = pinyinFirstLetter.charAt(0);
        return c;
    }

    public String getStr() {
        return str;
    }

    public void setStr(String str) {
        this.str = str;
    }
}

AndroidUtilCode 的 pinyinutil


        List<CompareData> listDatas = new ArrayList<CompareData>() {{
            add(new CompareData("张三"));
            add(new CompareData("李四"));
            add(new CompareData("王麻子"));
            add(new CompareData("鬼脚七"));
            add(new CompareData("黄飞鸿"));
            add(new CompareData("小白兔"));
            add(new CompareData("白又白"));
            add(new CompareData("臭傻吊"));
        }};

        Collections.sort(listDatas);


        for (int i = 0; i < listDatas.size(); i++) {
            CompareData compareData = listDatas.get(i);
            System.out.println(compareData.getStr() + "");
        }

效果:

拼音带音标的尝试:

    compile 'com.github.open-android:pinyin4j:2.5.0'
 //-------------------指定格式转换----------------------------
        HanyuPinyinOutputFormat format = new HanyuPinyinOutputFormat();

        // UPPERCASE:大写  (ZHONG)
        // LOWERCASE:小写  (zhong)
        format.setCaseType(HanyuPinyinCaseType.LOWERCASE);//输出小写

        // WITHOUT_TONE:无音标  (zhong)
        // WITH_TONE_NUMBER:1-4数字表示音标  (zhong4)
        // WITH_TONE_MARK:直接用音标符(必须WITH_U_UNICODE否则异常)  (zhòng)
        format.setToneType(HanyuPinyinToneType.WITH_TONE_MARK);

        // WITH_V:用v表示ü  (nv)
        // WITH_U_AND_COLON:用"u:"表示ü  (nu:)
        // WITH_U_UNICODE:直接用ü (nü)
        format.setVCharType(HanyuPinyinVCharType.WITH_U_UNICODE);

        String[] hao = new String[0];
        try {
            hao = PinyinHelper.toHanyuPinyinStringArray('你', format);
        } catch (BadHanyuPinyinOutputFormatCombination badHanyuPinyinOutputFormatCombination) {
            badHanyuPinyinOutputFormatCombination.printStackTrace();
        }

        for (String s : hao) {
            System.out.println(s);
        }

如果是多音字那么就会有俩个,

可以结合我上面的比较类直接实现多功能

 

 

 

显示全文