Android进阶学习-使用Canvas自定义ListView的字母索引列表(6)

首先我们来看看效果图:

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

实现左边是ListView,右边是我们的自定义控件.说下几个要点的思路:

    1.左边的item的layout是自定义的,每个item的layout都是由sortKey和data来组成,sortKey就是上面的字母部分,data就是要显示的内容.然后我们的itemBean需要两个属性firstLetter(首字母)和data(要显示的内容),另外我们还需要去实现Comparable接口,使列表可以进行排序,这样的话我们的数据就能够聚集到一起了.

    2.关键的还有就是怎么去控制sortKey只会去显示一次,考虑一下我们可以使用一个Map来保存已经出现的字母,键值是字母,返回值是位置,因为当键值不存在的时候返回的是0,所以我们要控制我们的data索引是从1开始的.一开始我们就去索引所有字母应该出现的位置,放到Map集合里面,然后在Adapter的getView方法里面判断是否显示sortKey

    3.然后对于右边的字母被点击,我们需要设置一个回调接口

    4.然后就是中文的处理了,对于中文的话我们可以使用一个拼音转换的工具类,可以把中文转换成拼音,我们取结果的第一个字母

 

开始编码吧.

    a.新建我们的item_data.xml布局文件:    

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <TextView
        android:id="@+id/sortKey"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="#80000000"
        android:padding="8dp"
        android:text="Z"
        android:textSize="16sp"
        android:textStyle="bold" />

    <TextView
        android:id="@+id/data"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:padding="3dp"
        android:text="湛江"
        android:layout_marginLeft="20dp"
        android:textSize="14sp" />


</LinearLayout>

    b.贴上我们的工具类

package com.example.august.sortkeylist;

import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Set;

public class ChineseToEnglish {
    private static LinkedHashMap spellMap = null;

    static {
        if (spellMap == null) {
            spellMap = new LinkedHashMap(500);
        }
        initialize();
    }

    private ChineseToEnglish() {

    }

    private static void spellPut(String spell, int ascii) {
        spellMap.put(spell, new Integer(ascii));
    }

    private static void initialize() {
        spellPut("a", -20319);
        spellPut("ai", -20317);
        spellPut("an", -20304);
        spellPut("ang", -20295);
        spellPut("ao", -20292);
        spellPut("ba", -20283);
        spellPut("bai", -20265);
        spellPut("ban", -20257);
        spellPut("bang", -20242);
        spellPut("bao", -20230);
        spellPut("bei", -20051);
        spellPut("ben", -20036);
        spellPut("beng", -20032);
        spellPut("bi", -20026);
        spellPut("bian", -20002);
        spellPut("biao", -19990);
        spellPut("bie", -19986);
        spellPut("bin", -19982);
        spellPut("bing", -19976);
        spellPut("bo", -19805);
        spellPut("bu", -19784);
        spellPut("ca", -19775);
        spellPut("cai", -19774);
        spellPut("can", -19763);
        spellPut("cang", -19756);
        spellPut("cao", -19751);
        spellPut("ce", -19746);
        spellPut("ceng", -19741);
        spellPut("cha", -19739);
        spellPut("chai", -19728);
        spellPut("chan", -19725);
        spellPut("chang", -19715);
        spellPut("chao", -19540);
        spellPut("che", -19531);
        spellPut("chen", -19525);
        spellPut("cheng", -19515);
        spellPut("chi", -19500);
        spellPut("chong", -19484);
        spellPut("chou", -19479);
        spellPut("chu", -19467);
        spellPut("chuai", -19289);
        spellPut("chuan", -19288);
        spellPut("chuang", -19281);
        spellPut("chui", -19275);
        spellPut("chun", -19270);
        spellPut("chuo", -19263);
        spellPut("ci", -19261);
        spellPut("cong", -19249);
        spellPut("cou", -19243);
        spellPut("cu", -19242);
        spellPut("cuan", -19238);
        spellPut("cui", -19235);
        spellPut("cun", -19227);
        spellPut("cuo", -19224);
        spellPut("da", -19218);
        spellPut("dai", -19212);
        spellPut("dan", -19038);
        spellPut("dang", -19023);
        spellPut("dao", -19018);
        spellPut("de", -19006);
        spellPut("deng", -19003);
        spellPut("di", -18996);
        spellPut("dian", -18977);
        spellPut("diao", -18961);
        spellPut("die", -18952);
        spellPut("ding", -18783);
        spellPut("diu", -18774);
        spellPut("dong", -18773);
        spellPut("dou", -18763);
        spellPut("du", -18756);
        spellPut("duan", -18741);
        spellPut("dui", -18735);
        spellPut("dun", -18731);
        spellPut("duo", -18722);
        spellPut("e", -18710);
        spellPut("en", -18697);
        spellPut("er", -18696);
        spellPut("fa", -18526);
        spellPut("fan", -18518);
        spellPut("fang", -18501);
        spellPut("fei", -18490);
        spellPut("fen", -18478);
        spellPut("feng", -18463);
        spellPut("fo", -18448);
        spellPut("fou", -18447);
        spellPut("fu", -18446);
        spellPut("ga", -18239);
        spellPut("gai", -18237);
        spellPut("gan", -18231);
        spellPut("gang", -18220);
        spellPut("gao", -18211);
        spellPut("ge", -18201);
        spellPut("gei", -18184);
        spellPut("gen", -18183);
        spellPut("geng", -18181);
        spellPut("gong", -18012);
        spellPut("gou", -17997);
        spellPut("gu", -17988);
        spellPut("gua", -17970);
        spellPut("guai", -17964);
        spellPut("guan", -17961);
        spellPut("guang", -17950);
        spellPut("gui", -17947);
        spellPut("gun", -17931);
        spellPut("guo", -17928);
        spellPut("ha", -17922);
        spellPut("hai", -17759);
        spellPut("han", -17752);
        spellPut("hang", -17733);
        spellPut("hao", -17730);
        spellPut("he", -17721);
        spellPut("hei", -17703);
        spellPut("hen", -17701);
        spellPut("heng", -17697);
        spellPut("hong", -17692);
        spellPut("hou", -17683);
        spellPut("hu", -17676);
        spellPut("hua", -17496);
        spellPut("huai", -17487);
        spellPut("huan", -17482);
        spellPut("huang", -17468);
        spellPut("hui", -17454);
        spellPut("hun", -17433);
        spellPut("huo", -17427);
        spellPut("ji", -17417);
        spellPut("jia", -17202);
        spellPut("jian", -17185);
        spellPut("jiang", -16983);
        spellPut("jiao", -16970);
        spellPut("jie", -16942);
        spellPut("jin", -16915);
        spellPut("jing", -16733);
        spellPut("jiong", -16708);
        spellPut("jiu", -16706);
        spellPut("ju", -16689);
        spellPut("juan", -16664);
        spellPut("jue", -16657);
        spellPut("jun", -16647);
        spellPut("ka", -16474);
        spellPut("kai", -16470);
        spellPut("kan", -16465);
        spellPut("kang", -16459);
        spellPut("kao", -16452);
        spellPut("ke", -16448);
        spellPut("ken", -16433);
        spellPut("keng", -16429);
        spellPut("kong", -16427);
        spellPut("kou", -16423);
        spellPut("ku", -16419);
        spellPut("kua", -16412);
        spellPut("kuai", -16407);
        spellPut("kuan", -16403);
        spellPut("kuang", -16401);
        spellPut("kui", -16393);
        spellPut("kun", -16220);
        spellPut("kuo", -16216);
        spellPut("la", -16212);
        spellPut("lai", -16205);
        spellPut("lan", -16202);
        spellPut("lang", -16187);
        spellPut("lao", -16180);
        spellPut("le", -16171);
        spellPut("lei", -16169);
        spellPut("leng", -16158);
        spellPut("li", -16155);
        spellPut("lia", -15959);
        spellPut("lian", -15958);
        spellPut("liang", -15944);
        spellPut("liao", -15933);
        spellPut("lie", -15920);
        spellPut("lin", -15915);
        spellPut("ling", -15903);
        spellPut("liu", -15889);
        spellPut("long", -15878);
        spellPut("lou", -15707);
        spellPut("lu", -15701);
        spellPut("lv", -15681);
        spellPut("luan", -15667);
        spellPut("lue", -15661);
        spellPut("lun", -15659);
        spellPut("luo", -15652);
        spellPut("ma", -15640);
        spellPut("mai", -15631);
        spellPut("man", -15625);
        spellPut("mang", -15454);
        spellPut("mao", -15448);
        spellPut("me", -15436);
        spellPut("mei", -15435);
        spellPut("men", -15419);
        spellPut("meng", -15416);
        spellPut("mi", -15408);
        spellPut("mian", -15394);
        spellPut("miao", -15385);
        spellPut("mie", -15377);
        spellPut("min", -15375);
        spellPut("ming", -15369);
        spellPut("miu", -15363);
        spellPut("mo", -15362);
        spellPut("mou", -15183);
        spellPut("mu", -15180);
        spellPut("na", -15165);
        spellPut("nai", -15158);
        spellPut("nan", -15153);
        spellPut("nang", -15150);
        spellPut("nao", -15149);
        spellPut("ne", -15144);
        spellPut("nei", -15143);
        spellPut("nen", -15141);
        spellPut("neng", -15140);
        spellPut("ni", -15139);
        spellPut("nian", -15128);
        spellPut("niang", -15121);
        spellPut("niao", -15119);
        spellPut("nie", -15117);
        spellPut("nin", -15110);
        spellPut("ning", -15109);
        spellPut("niu", -14941);
        spellPut("nong", -14937);
        spellPut("nu", -14933);
        spellPut("nv", -14930);
        spellPut("nuan", -14929);
        spellPut("nue", -14928);
        spellPut("nuo", -14926);
        spellPut("o", -14922);
        spellPut("ou", -14921);
        spellPut("pa", -14914);
        spellPut("pai", -14908);
        spellPut("pan", -14902);
        spellPut("pang", -14894);
        spellPut("pao", -14889);
        spellPut("pei", -14882);
        spellPut("pen", -14873);
        spellPut("peng", -14871);
        spellPut("pi", -14857);
        spellPut("pian", -14678);
        spellPut("piao", -14674);
        spellPut("pie", -14670);
        spellPut("pin", -14668);
        spellPut("ping", -14663);
        spellPut("po", -14654);
        spellPut("pu", -14645);
        spellPut("qi", -14630);
        spellPut("qia", -14594);
        spellPut("qian", -14429);
        spellPut("qiang", -14407);
        spellPut("qiao", -14399);
        spellPut("qie", -14384);
        spellPut("qin", -14379);
        spellPut("qing", -14368);
        spellPut("qiong", -14355);
        spellPut("qiu", -14353);
        spellPut("qu", -14345);
        spellPut("quan", -14170);
        spellPut("que", -14159);
        spellPut("qun", -14151);
        spellPut("ran", -14149);
        spellPut("rang", -14145);
        spellPut("rao", -14140);
        spellPut("re", -14137);
        spellPut("ren", -14135);
        spellPut("reng", -14125);
        spellPut("ri", -14123);
        spellPut("rong", -14122);
        spellPut("rou", -14112);
        spellPut("ru", -14109);
        spellPut("ruan", -14099);
        spellPut("rui", -14097);
        spellPut("run", -14094);
        spellPut("ruo", -14092);
        spellPut("sa", -14090);
        spellPut("sai", -14087);
        spellPut("san", -14083);
        spellPut("sang", -13917);
        spellPut("sao", -13914);
        spellPut("se", -13910);
        spellPut("sen", -13907);
        spellPut("seng", -13906);
        spellPut("sha", -13905);
        spellPut("shai", -13896);
        spellPut("shan", -13894);
        spellPut("shang", -13878);
        spellPut("shao", -13870);
        spellPut("she", -13859);
        spellPut("shen", -13847);
        spellPut("sheng", -13831);
        spellPut("shi", -13658);
        spellPut("shou", -13611);
        spellPut("shu", -13601);
        spellPut("shua", -13406);
        spellPut("shuai", -13404);
        spellPut("shuan", -13400);
        spellPut("shuang", -13398);
        spellPut("shui", -13395);
        spellPut("shun", -13391);
        spellPut("shuo", -13387);
        spellPut("si", -13383);
        spellPut("song", -13367);
        spellPut("sou", -13359);
        spellPut("su", -13356);
        spellPut("suan", -13343);
        spellPut("sui", -13340);
        spellPut("sun", -13329);
        spellPut("suo", -13326);
        spellPut("ta", -13318);
        spellPut("tai", -13147);
        spellPut("tan", -13138);
        spellPut("tang", -13120);
        spellPut("tao", -13107);
        spellPut("te", -13096);
        spellPut("teng", -13095);
        spellPut("ti", -13091);
        spellPut("tian", -13076);
        spellPut("tiao", -13068);
        spellPut("tie", -13063);
        spellPut("ting", -13060);
        spellPut("tong", -12888);
        spellPut("tou", -12875);
        spellPut("tu", -12871);
        spellPut("tuan", -12860);
        spellPut("tui", -12858);
        spellPut("tun", -12852);
        spellPut("tuo", -12849);
        spellPut("wa", -12838);
        spellPut("wai", -12831);
        spellPut("wan", -12829);
        spellPut("wang", -12812);
        spellPut("wei", -12802);
        spellPut("wen", -12607);
        spellPut("weng", -12597);
        spellPut("wo", -12594);
        spellPut("wu", -12585);
        spellPut("xi", -12556);
        spellPut("xia", -12359);
        spellPut("xian", -12346);
        spellPut("xiang", -12320);
        spellPut("xiao", -12300);
        spellPut("xie", -12120);
        spellPut("xin", -12099);
        spellPut("xing", -12089);
        spellPut("xiong", -12074);
        spellPut("xiu", -12067);
        spellPut("xu", -12058);
        spellPut("xuan", -12039);
        spellPut("xue", -11867);
        spellPut("xun", -11861);
        spellPut("ya", -11847);
        spellPut("yan", -11831);
        spellPut("yang", -11798);
        spellPut("yao", -11781);
        spellPut("ye", -11604);
        spellPut("yi", -11589);
        spellPut("yin", -11536);
        spellPut("ying", -11358);
        spellPut("yo", -11340);
        spellPut("yong", -11339);
        spellPut("you", -11324);
        spellPut("yu", -11303);
        spellPut("yuan", -11097);
        spellPut("yue", -11077);
        spellPut("yun", -11067);
        spellPut("za", -11055);
        spellPut("zai", -11052);
        spellPut("zan", -11045);
        spellPut("zang", -11041);
        spellPut("zao", -11038);
        spellPut("ze", -11024);
        spellPut("zei", -11020);
        spellPut("zen", -11019);
        spellPut("zeng", -11018);
        spellPut("zha", -11014);
        spellPut("zhai", -10838);
        spellPut("zhan", -10832);
        spellPut("zhang", -10815);
        spellPut("zhao", -10800);
        spellPut("zhe", -10790);
        spellPut("zhen", -10780);
        spellPut("zheng", -10764);
        spellPut("zhi", -10587);
        spellPut("zhong", -10544);
        spellPut("zhou", -10533);
        spellPut("zhu", -10519);
        spellPut("zhua", -10331);
        spellPut("zhuai", -10329);
        spellPut("zhuan", -10328);
        spellPut("zhuang", -10322);
        spellPut("zhui", -10315);
        spellPut("zhun", -10309);
        spellPut("zhuo", -10307);
        spellPut("zi", -10296);
        spellPut("zong", -10281);
        spellPut("zou", -10274);
        spellPut("zu", -10270);
        spellPut("zuan", -10262);
        spellPut("zui", -10260);
        spellPut("zun", -10256);
        spellPut("zuo", -10254);
    }

    /**
     * 获得单个汉字的Ascii.
     * @param cn char 汉字字符
     * @return int 错误返回 0,否则返回ascii
     */
    public static int getCnAscii(char cn) {
        byte[] bytes = (String.valueOf(cn)).getBytes();
        if (bytes == null || bytes.length > 2 || bytes.length <= 0) { //错误
            return 0;
        }
        if (bytes.length == 1) { //英文字符
            return bytes[0];
        }
        if (bytes.length == 2) { //中文字符
            int hightByte = 256 + bytes[0];
            int lowByte = 256 + bytes[1];

            int ascii = (256 * hightByte + lowByte) - 256 * 256;

            return ascii;
        }
        return 0; //错误
    }

    /**
     * 根据ASCII码到SpellMap中查找对应的拼音
     * @param ascii int
     * 字符对应的ASCII
     * @return String
     * 拼音,首先判断ASCII是否>0&<160,如果是返回对应的字符,
     * <BR>否则到SpellMap中查找,如果没有找到拼音,则返回null,如果找到则返回拼音.
     */
    public static String getSpellByAscii(int ascii) {
        if (ascii > 0 && ascii < 160) { //单字符
            return String.valueOf( (char) ascii);
        }

        if (ascii < -20319 || ascii > -10247) { //不知道的字符
            return null;
        }

        Set keySet = spellMap.keySet();
        Iterator it = keySet.iterator();

        String spell0 = null;
        String spell = null;

        int asciiRang0 = -20319;
        int asciiRang;
        while (it.hasNext()) {
            spell = (String) it.next();
            Object valObj = spellMap.get(spell);
            if (valObj instanceof Integer) {
                asciiRang = ( (Integer) valObj).intValue();

                if (ascii >= asciiRang0 && ascii < asciiRang) { //区间找到
                    return (spell0 == null) ? spell : spell0;
                }
                else {
                    spell0 = spell;
                    asciiRang0 = asciiRang;
                }
            }
        }

        return null;

    }

    /**
     * 返回字符串的全拼,是汉字转化为全拼,其它字符不进行转换
     * @param cnStr String
     * 字符串
     * @return String
     * 转换成全拼后的字符串
     */
    public static String getFullSpell(String cnStr) {
        if (null == cnStr || "".equals(cnStr.trim())) {
            return cnStr;
        }

        char[] chars = cnStr.toCharArray();
        StringBuffer retuBuf = new StringBuffer();
        for (int i = 0, Len = chars.length; i < Len; i++) {
            int ascii = getCnAscii(chars[i]);
            if (ascii == 0) { //取ascii时出错
                retuBuf.append(chars[i]);
            }
            else {
                String spell = getSpellByAscii(ascii);
                if (spell == null) {
                    retuBuf.append(chars[i]);
                }
                else {
                    retuBuf.append(spell);
                } // end of if spell == null
            } // end of if ascii <= -20400
        } // end of for

        return retuBuf.toString();
    }

    /**
     * 第一个字取全拼,后面的字取首字母
     * @param cnStr
     * @return 返回转换后的拼
     */
    public static String getFirstSpell(String cnStr) {
        if (null == cnStr || "".equals(cnStr.trim())) {
            return cnStr;
        }

        char[] chars = cnStr.toCharArray();
        StringBuffer retuBuf = new StringBuffer();
        for (int i = 0, Len = chars.length; i < Len; i++) {
            int ascii = getCnAscii(chars[i]);

            if (ascii == 0) { //取ascii时出错
                retuBuf.append(chars[i]);
            }
            else {
                String spell = getSpellByAscii(ascii);
                if (spell == null) {
                    retuBuf.append(chars[i]);
                }
                else {
                    if (i == 0) { //第一个字取全拼
                        retuBuf.append(spell);
                    }
                    else { //后面的字取首字母
                        retuBuf.append(spell.substring(0, 1));
                    }
                }
            }

        } // end of for
        return retuBuf.toString();
    }

}

    c.新建我们的DataBean.java

package com.example.august.sortkeylist;

/**
 * Created by August on 16/5/11.
 */
public class DataBean implements Comparable<DataBean> {
    private String data;
    private char firstLetter;

    public String getData() {
        return data;
    }

    public void setData(String data) {
        this.data = data;
        firstLetter = ChineseToEnglish.getFirstSpell(data).charAt(0);
    }

    public char getFirstLetter() {
        return firstLetter;
    }


    /**
     * 使用Comparable接口,使数据可排序
     * @param dataBean
     * @return
     */
    @Override
    public int compareTo(DataBean dataBean) {
        if (firstLetter > dataBean.firstLetter) {
            return 1;
        } else if (firstLetter < dataBean.firstLetter) {
            return -1;
        } else {
            return 0;
        }
    }
}

    d.新建我们的DataAdapter.java代码文件:

package com.example.august.sortkeylist;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;

import java.util.HashMap;
import java.util.Map;

/**
 * Created by August on 16/5/11.
 */
public class DataAdapter extends BaseAdapter {

    private DataBean[] mDatas;

    /**
     * 用来保存已经每个字母的第一个数据的位置
     */
    private Map<String, Integer> marks = new HashMap<>();


    public DataAdapter(DataBean[] mDatas) {
        this.mDatas = mDatas;

        for (int i = 0; i < mDatas.length; i++) {
            if (marks.get(String.valueOf(mDatas[i].getFirstLetter())) == null) {
                marks.put(String.valueOf(mDatas[i].getFirstLetter()), i + 1);
            }
        }
        /**
         * 初始化索引所有字母的第一个数据的位置
         * 键值为字母,值为位置+1,因为Map默认不存在时返回0,所以我们位置需要从1开始
         */


    }

    @Override
    public int getCount() {
        return mDatas.length;
    }

    @Override
    public Object getItem(int i) {
        return mDatas[i];
    }

    @Override
    public long getItemId(int i) {
        return i;
    }

    @Override
    public View getView(int i, View view, ViewGroup viewGroup) {

        ViewHolder holder = null;

        if (view == null) {
            view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.item_data, null);
            holder = new ViewHolder();
            holder.data = (TextView) view.findViewById(R.id.data);
            holder.sortKey = (TextView) view.findViewById(R.id.sortKey);
            view.setTag(holder);
        } else {
            holder = (ViewHolder) view.getTag();
        }
        holder.data.setText(mDatas[i].getData());
        /**
         * 上面都是普通Adapter的代码
         */


        /**
         * 下面是开始判断,当当前item的位置等于刚开始索引出来的位置时,我们把sortKey给显示出来
         * 否则隐藏掉
         */
        if (marks.get(String.valueOf(mDatas[i].getFirstLetter())) == i + 1) {
            holder.sortKey.setText(String.valueOf(mDatas[i].getFirstLetter()));
            holder.sortKey.setVisibility(View.VISIBLE);
        } else {
            holder.sortKey.setVisibility(View.GONE);
        }


        return view;
    }

    class ViewHolder {
        TextView data;
        TextView sortKey;
    }
    
}

    e.现在我们的ListView部分基本完成,我们需要数据:

package com.example.august.sortkeylist;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.Window;
import android.widget.ListView;

import java.util.Arrays;

public class MainActivity extends AppCompatActivity {

    private ListView mListView;
    private DataBean[] mDatas;
    private DataAdapter mAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_main);
        mListView = (ListView) findViewById(R.id.mListView);
        mDatas = new DataBean[500];
        for (int i = 0; i < 500; i++) {
            DataBean dataBean = new DataBean();
            dataBean.setData(String.valueOf((char) (65 + Math.random() * 26))
                    + String.valueOf((char) (65 + Math.random() * 26))
                    + String.valueOf((char) (65 + Math.random() * 26)));
            mDatas[i] = dataBean;
        }

        Arrays.sort(mDatas);
        /**
         * 使用了Comparable接口,所以可以进行排序了
         */

        mAdapter = new DataAdapter(mDatas);

        mListView.setAdapter(mAdapter);
    }


}

    f.下面开始编写SortListView.java最简单时的代码:

package com.example.august.sortkeylist;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.util.TypedValue;
import android.view.ViewGroup;

/**
 * Created by August on 16/5/11.
 */
public class SortListView extends ViewGroup {

    /**
     * 这是索引的26个字母
     */
    private String[] alphabet = new String[]{"A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N"
            , "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"};

    private Paint mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);


    public SortListView(Context context) {
        super(context);
    }


    public SortListView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public SortListView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }


    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    }


    @Override
    protected void onLayout(boolean b, int i, int i1, int i2, int i3) {

    }


    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);

        mPaint.setColor(Color.GRAY);
        mPaint.setTextSize(TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 12, getResources().getDisplayMetrics()));
        int eachHeight = getHeight() / alphabet.length;
        int width = getWidth();
        for (int i = 0; i < alphabet.length; i++) {
            float x = width / 2 - mPaint.measureText(alphabet[i]) / 2;
            canvas.drawText(alphabet[i], x, eachHeight * (i + 1), mPaint);
        }

        /**
         * 每个字母占据的高度是当前 父容器的高度/字母个数
         * 然后我们把每个字母给画出来
         */
    }
}

    g.现在我们需要给SortListView来添加回调和点击事件:

    private OnTouchListener mOnTouchListener;

    public interface OnTouchListener {
        public void onTouch(String s);
    }

    /**
     * 上面是我们的回调接口和当前对象持有的回调
     */

    @Override
    public boolean dispatchTouchEvent(MotionEvent event) {
        /**
         * 我们去截取按下和移动的事件,通过点击的Y坐标我们可以轻易计算出点下的位置是对应哪个字母的索引
         * 计算是根据公式 当前点击的Y坐标/当前View的总高度 = 字母索引/所有字母长度
         * 然后把字母作为参数给传给回调
         */
        if (mOnTouchListener != null) {
            if (event.getAction() == MotionEvent.ACTION_DOWN
                    || event.getAction() == MotionEvent.ACTION_MOVE) {
                int index = (int) (event.getY() / (getHeight() / alphabet.length));
                if (index > -1 && index < alphabet.length) {
                    mOnTouchListener.onTouch(alphabet[index]);
                }
            }
        }
        return super.dispatchTouchEvent(event);
    }

    h.最终我们的SortListView代码就完成了,最后是长这样的:

package com.example.august.sortkeylist;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.util.TypedValue;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.ViewGroup;

/**
 * Created by August on 16/5/11.
 */
public class SortListView extends ViewGroup {

    /**
     * 这是索引的26个字母
     */
    private String[] alphabet = new String[]{"A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N"
            , "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"};

    private Paint mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);

    private OnTouchListener mOnTouchListener;

    public interface OnTouchListener {
        public void onTouch(String s);
    }

    /**
     * 上面是我们的回调接口和当前对象持有的回调
     */


    public SortListView(Context context) {
        super(context);
    }

    public void setmOnTouchListener(OnTouchListener mOnTouchListener) {
        this.mOnTouchListener = mOnTouchListener;
    }

    public SortListView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public SortListView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }


    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent event) {
        /**
         * 我们去截取按下和移动的事件,通过点击的Y坐标我们可以轻易计算出点下的位置是对应哪个字母的索引
         * 计算是根据公式 当前点击的Y坐标/当前View的总高度 = 字母索引/所有字母长度
         * 然后把字母作为参数给传给回调
         */
        if (mOnTouchListener != null) {
            if (event.getAction() == MotionEvent.ACTION_DOWN
                    || event.getAction() == MotionEvent.ACTION_MOVE) {
                int index = (int) (event.getY() / (getHeight() / alphabet.length));
                if (index > -1 && index < alphabet.length) {
                    mOnTouchListener.onTouch(alphabet[index]);
                }
            }
        }
        return super.dispatchTouchEvent(event);
    }

    @Override
    protected void onLayout(boolean b, int i, int i1, int i2, int i3) {

    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                setBackgroundColor(Color.parseColor("#bebebe"));
                break;
            case MotionEvent.ACTION_UP:
                setBackgroundColor(Color.WHITE);
                break;
        }
        return true;
        //按下的时候给它设置一个颜色
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);

        mPaint.setColor(Color.GRAY);
        mPaint.setTextSize(TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 12, getResources().getDisplayMetrics()));
        int eachHeight = getHeight() / alphabet.length;
        int width = getWidth();
        for (int i = 0; i < alphabet.length; i++) {
            float x = width / 2 - mPaint.measureText(alphabet[i]) / 2;
            canvas.drawText(alphabet[i], x, eachHeight * (i + 1), mPaint);
        }

        /**
         * 每个字母占据的高度是当前 父容器的高度/字母个数
         * 然后我们可以把每个字母给画出来
         */
    }
}

    i.最后我们在DataAdapter添加一个方法,可以通过给定的字母返回对应Map里面的位置

    public Integer getPosition(String s) {
        Integer result = marks.get(s);
        if (result != null) {
            result = result - 1;
        }
        return result;
    }

    j.至此我们就完成了空间部分的代码了,下面是调用的代码:

package com.example.august.sortkeylist;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.Window;
import android.widget.ListView;

import java.util.Arrays;

public class MainActivity extends AppCompatActivity {

    private ListView mListView;
    private SortListView mSortListView;
    private DataBean[] mDatas;
    private DataAdapter mAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_main);
        mListView = (ListView) findViewById(R.id.mListView);
        mSortListView = (SortListView) findViewById(R.id.mSortList);
        mDatas = new DataBean[500];
        for (int i = 0; i < 500; i++) {
            DataBean dataBean = new DataBean();
            dataBean.setData(String.valueOf((char) (65 + Math.random() * 26))
                    + String.valueOf((char) (65 + Math.random() * 26))
                    + String.valueOf((char) (65 + Math.random() * 26)));
            mDatas[i] = dataBean;
        }

        Arrays.sort(mDatas);

        mAdapter = new DataAdapter(mDatas);
        mSortListView.setmOnTouchListener(new SortListView.OnTouchListener() {
            @Override
            public void onTouch(String s) {
                Integer index = mAdapter.getPosition(s);
                if (index != null) {
                    mListView.setSelection(index);
                }
            }
        });
        mListView.setAdapter(mAdapter);
    }


}

 

转载于:https://my.oschina.net/august1996/blog/676525

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值