安卓中通讯录的实现

首先,布局

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context="com.example.zy.officesystem.fragment.ContactsFragment">

    <SearchView
        android:id="@+id/sv_search_contacts"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:queryHint="搜索"
        android:iconifiedByDefault="false"
        android:background="@android:color/darker_gray"
        android:queryBackground="@drawable/searchview_background"
        android:padding="5dp"
        android:focusable="false"

        >
    </SearchView>

    <View
        android:layout_width="match_parent"
        android:layout_height="5dp"
        android:alpha="0.5"
        android:background="@android:color/darker_gray" />


    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <android.support.v7.widget.RecyclerView
            android:id="@+id/rv_my_contacts"
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="12">

        </android.support.v7.widget.RecyclerView>

        <ListView
            android:id="@+id/lv_first_letter"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:layout_gravity="center"
            android:divider="@null">

        </ListView>


    </LinearLayout>


</LinearLayout>

页面效果


其次,实现代码部分

一文件清单

由于adapter大同小异,这里略过

1数据文件

Contacts类


public class Contacts implements Comparable<Contacts>{
    private String name;
    private String teleNumber;
    private String position;
    private int headPicId;
    private String spelling;
    private boolean isFirst=false;

    public Contacts(String name, String teleNumber, String position,int headPicId,CharacterParser characterParser) {
        this.name = name;
        this.teleNumber = teleNumber;
        this.position=position;
        this.headPicId = headPicId;
        characterParser.setResource(name);//通过拼音转换类,把汉字转换成拼音//
        this.spelling=characterParser.getSpelling();
    }

    public String getName() {
        return name;
    }

    public String getTeleNumber() {
        return teleNumber;
    }

    public String getPosition() {
        return position;
    }

    public int getHeadPicId() {
        return headPicId;
    }

    public String getSpelling() {
        return spelling;
    }

    public boolean getIsFirst() {
        return isFirst;
    }

    public void setIsFirst(boolean isFirst) {
        this.isFirst = isFirst;
    }

    @Override
    public int compareTo(@NonNull Contacts o) {
        return this.spelling.compareTo(o.spelling);
    }

    @Override
    public String toString() {
        String name=getName();

        return "name="+name+",isFirst="+isFirst;
    }
}

关于比较排序,Java中有Comparable接口(实现compareTo()方法)和Comparator类两种方法

参考资料

https://www.cnblogs.com/Kevin-mao/p/5912775.html

这里是让Contact实现了Compareable接口

对于List<Contact> list,直接调用Conllections.sort(list),即可获得排序后的list.

2.LetterData类

public class LetterData {
    private String letter;
    private int position;//记录首次出现首字母的RecyclerView中的位置//

    public LetterData(String letter, int position) {
        this.letter = letter;
        this.position = position;
    }

    public String getLetter() {
        return letter;
    }

    public void setLetter(String letter) {
        this.letter = letter;
    }

    public int getPosition() {
        return position;
    }

    public void setPosition(int position) {
        this.position = position;
    }

    @Override
    public String toString() {
        return "letter="+getLetter()+",position="+getPosition();
    }
}
3.拼音转换类

 资料

https://blog.csdn.net/xiaanming/article/details/12684155

如何从汉字获得拼音以及首字母

受益于资料中作者的工作,首先把汉字转换成GB2312码,然后根据GB2312的编码原则转成ASC2码,然后根据固定的汉语拼音构成,以及其对应的ASC2码库,从ASC2码转换成汉语拼音

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

    public static CharacterParser getInstance() {
        return characterParser;
    }

    public String getResource() {
        return resource;
    }

    public void setResource(String resource) {
        this.resource = resource;
    }

    /**
     * 汉字转成ASCII码 * * @param chs * @return
     */
    private int getChsAscii(String chs) {
        int asc = 0;
        try {
            byte[] bytes = chs.getBytes("GB2312");
            if (bytes == null || bytes.length > 2 || bytes.length <= 0) {
                throw new RuntimeException("illegal resource string");
            }
            if (bytes.length == 1) {
                asc = bytes[0];
            }
            if (bytes.length == 2) {
                int hightByte = 256 + bytes[0];
                int lowByte = 256 + bytes[1];
                asc = (256 * hightByte + lowByte) - 256 * 256;
            }
        } catch (Exception e) {
            System.out.println("ERROR:ChineseSpelling.class-getChsAscii(String chs)" + e);
        }
        return asc;
    }

    /**
     * 单字解析 * * @param str * @return
     */
    public String convert(String str) {
        String result = null;
        int ascii = getChsAscii(str);
        if (ascii > 0 && ascii < 160) {
            result = String.valueOf((char) ascii);
        } else {
            for (int i = (pyvalue.length - 1); i >= 0; i--) {
                if (pyvalue[i] <= ascii) {
                    result = pystr[i];
                    break;
                }
            }
        }
        return result;
    }

    /**
     * 词组解析 * * @param chs * @return
     */
    public String getSelling(String chs) {
        String key, value;
        buffer = new StringBuilder();
        for (int i = 0; i < chs.length(); i++) {
            key = chs.substring(i, i + 1);
            if (key.getBytes().length >= 2) {
                value = (String) convert(key);
                if (value == null) {
                    value = "unknown";
                }
            } else {
                value = key;
            }
            buffer.append(value);
        }
        return buffer.toString();
    }

    public String getSpelling() {
        return this.getSelling(this.getResource());
    }

}

关于gb2312,参考

http://xuepengcheng.iteye.com/blog/854739

https://www.cnblogs.com/hehheai/p/6510879.html

gb2312首先判断byte的最高位,0,本字节就是ASC2码;1,则取两个字节作为1个汉字。这两个字节的最高位代表符号为负,即height=256+btye[0],lower=256+byte[1],取剩下的7位,然后height*256+lower,然后我猜测可能是需要取补码,所以需要减去256*256,即pinyinvalue字库的来源

4活动文件

public class ContactsFragment extends Fragment{

    @BindView(R.id.sv_search_contacts)
    SearchView svSearchContacts;
    @BindView(R.id.rv_my_contacts)
    RecyclerView rvMyContacts;
    @BindView(R.id.lv_first_letter)
    ListView lvFirstLetter;
    Unbinder unbinder;


   //Rv填充的联系人列表
    private List<Contacts> contactsList = new ArrayList<>();
    //Lv填充的首字母清单
    private List<String> letterList=new ArrayList<>();
    //lv真正填充的首字母列表
    private List<LetterData> letterDataList=new ArrayList<>();

//    拼音工具类实例
    private CharacterParser characterParser=CharacterParser.getInstance();
    private String TAG = "ContactsFragment";
//    RV滚动监听需要的布局管理器
    private LinearLayoutManager linear;
//    RV滚动监听的标志位
    private boolean move=false;
//    RV滚动监听的目的位置
    private int toPosition;


    public ContactsFragment() {
        // Required empty public constructor
    }

    public static ContactsFragment newInstance() {
        ContactsFragment fragment = new ContactsFragment();
        Bundle args = new Bundle();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
//        TODO test
        contactsList.add(new Contacts("王小明","15001243836","组员",R.drawable.pressed,characterParser));
        contactsList.add(new Contacts("王大明","15001243836","组员",R.drawable.pressed,characterParser));
        contactsList.add(new Contacts("陈文山","15001243836","组长",R.drawable.pressed,characterParser));
        contactsList.add(new Contacts("方文山","15001243836","组长",R.drawable.pressed,characterParser));
        contactsList.add(new Contacts("张鹏","15001243836","组员",R.drawable.pressed,characterParser));
        contactsList.add(new Contacts("张大大","15001243836","组员",R.drawable.pressed,characterParser));
        contactsList.add(new Contacts("李业辉","15001243836","组员",R.drawable.pressed,characterParser));
        contactsList.add(new Contacts("李登","15001243836","组员",R.drawable.pressed,characterParser));
        contactsList.add(new Contacts("尤利","15001243836","组员",R.drawable.pressed,characterParser));
        contactsList.add(new Contacts("尤东升","15001243836","组员",R.drawable.pressed,characterParser));
//          排序
        Collections.sort(contactsList);
        LogUtil.i(TAG, "onCreate: "+contactsList.toString());
//          初始化letterDataList
        letterDataList=initLetterList(contactsList);
    }

    private List<LetterData> initLetterList(List<Contacts> contactsList) {
        for (int i=0;i<contactsList.size();i++){
            String letter=contactsList.get(i).getSpelling().substring(0,1).toUpperCase();
            LogUtil.i(TAG, "initLetterList: letter="+letter);
            if (!letterList.contains(letter)){
                letterList.add(letter);
                LetterData letterData=new LetterData(letter,i);
                letterDataList.add(letterData);
                contactsList.get(i).setIsFirst(true);
                LogUtil.i(TAG, "initLetterList: position="+i);
            }
        }
        LogUtil.i(TAG, "initLetterList: letterList="+letterList.toString());
        LogUtil.i(TAG, "initLetterList: letterDataList="+letterDataList.toString());
        LogUtil.i(TAG, "initLetterList: contactsList="+contactsList.toString());
        return letterDataList;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_contacts, container, false);
        unbinder = ButterKnife.bind(this, view);
//          为RV和LV加载数据
        linear=new LinearLayoutManager(getContext(),LinearLayoutManager.VERTICAL,false);
        rvMyContacts.setLayoutManager(linear);
        ContactsAdapter adapter=new ContactsAdapter(contactsList);
        rvMyContacts.setAdapter(adapter);
        LetterDataAdapter adapter2=new LetterDataAdapter(getContext(),R.layout.layout_letter,letterDataList);
        lvFirstLetter.setAdapter(adapter2);
//        初始化监听器
        initListener();

        return view;
    }

    private void initListener() {
        svSearchContacts.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
            @Override
            public boolean onQueryTextSubmit(String query) {
                return false;
            }

//            搜索栏监听
            @Override
            public boolean onQueryTextChange(String newText) {
                List<Contacts> searchList=new ArrayList<>();
                if (newText.isEmpty()){
                    searchList=contactsList;
                }else {
                    for (Contacts contacts:contactsList){
                        if (contacts.getSpelling().contains(newText)){
                            searchList.add(contacts);
                        }
                    }
                }
                ContactsAdapter adapter3=new ContactsAdapter(searchList);
                rvMyContacts.setAdapter(adapter3);
                return true;
            }
        });
//        lv的点击监听
        lvFirstLetter.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                LetterData letterData=letterDataList.get(position);
                toPosition=letterData.getPosition();
                move(toPosition);
            }
        });

//        滚动监听
        rvMyContacts.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                if (move){
                    move=false;
                    int n=toPosition-linear.findFirstVisibleItemPosition();
                    if (n>0&&n<linear.getChildCount()){
                        int top=rvMyContacts.getChildAt(n).getTop();
                        rvMyContacts.smoothScrollBy(0,top);
                    }
                }
            }
        });
    }

//    lv点击中的move()方法,主要是重用了smoothScrollBy()方法
    private void move(int position) {
        int first=linear.findFirstVisibleItemPosition();
        int last=linear.findLastVisibleItemPosition();
        LogUtil.i(TAG, "move: position="+position);
        LogUtil.i(TAG, "move: first="+first);
        LogUtil.i(TAG, "move: last="+last);
        if (position<first){
            rvMyContacts.smoothScrollToPosition(position);
            LogUtil.i(TAG, "move: first front");
        }else if (position<=last){
            int top=rvMyContacts.getChildAt(position-first).getTop();
            rvMyContacts.smoothScrollBy(0,top);
            LogUtil.i(TAG, "move: top="+top);
        }else if (position>last){
            rvMyContacts.smoothScrollToPosition(position);
            move=true;
            LogUtil.i(TAG, "move: last-first="+(last-first));
        }
    }


    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }
}

最后是实现效果(不会上传gif图片)




填坑

1,通讯录中字母分组的角标,会出现混乱的情况

这种情况是因为Recyclerview本身的复用机制产生的.

角标的visibility属性在xml中默认为gone,

代码中设置角标时打开,visibility设置为visible

即使后续有item的角标代码中没有设置visibility属性,复用机制也会出现错位的角标

解决办法,代码中需要手动设置visibility为gone

参考https://segmentfault.com/q/1010000006217554?sort=created


2.实现过程中遇到的新的函数

RecyclerView.scrollToPosition(int i)直接定位滚动到指定的item位置

滚动方向:item相对于当前显示的item而定.item在屏幕上方,会从上往下滚动,直到item变成显示的第一条;item在屏幕中,不滚动;item在屏幕下方,从下往上滚动,item变成最后一条.

RecyclerView.smoothScrollToPosition(int i)增加平滑滚动的视觉效果,定位滚动到指定的item位置

RecyclerView.scrollBy(int x,int y) 按给定的坐标直接滚动到指定的位置

RecyclerView.SmoothScrollBy(int x,int y) 按给定的坐标直接滚动到指定的位置,增加平滑滚动的效果

View getChildAt(int index) 在集合中返回指定位置的视图。

int LayoutManager.findFirstVisibleItemPosition()返回RecyclerView中可见的第一个item的位置

5 种方法获取 View 的坐标{

        参考https://blog.csdn.net/u013872857/article/details/53750682

    View.getTop()、View.getLeft()、View.getBottom()、View.getRight();用于获取View相对于父容器的坐标

    View.getX()、View.getY();获取的是View左上角相对于父容器的坐标,当View没有发生平移操作时,getX()==getLeft()、getY==getTop()。

    View.getTranslationX()、View.getTranslationY();translationX与 translationY是View左上角相对于父容器的偏移量:translationX = getX() - getLeft(),当View未发生平移操作时,translationX 与translationY都为0。

    View.getLocationOnScreen(int[] position);获取View相对于整个屏幕的坐标。

    View.getLocationInWindow(int[] position);获取View相对于Window的坐标(忽略状态栏及ActionBar)。

}


猜你喜欢

转载自blog.csdn.net/rungby/article/details/80362109