Android中带检索功能的联系人列表实现

Android 中如何实现拼音检索的联系人列表,可以通过字母分组检索,实现过程和源代码如下。

演示

Android检索功能的联系人列表演示 Android检索功能的联系人列表演示

汉字转拼音

汉字转拼音的 jar 包 汉字转拼音的 jar 包

1
2
String pinyingStr = PinyinHelper.getShortPinyin(
           String.valueOf(charSequence).toLowerCase().trim());

获取分组Key(A,B,C….#)

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
@Nullable
private String getPingyingKey(String pinyinString) {
    //将拼音字符串转换为大写拼音
    if(pinyinString == null && pinyinString.length() == 0) return null;
    //获取大写拼音字符串的第一个字符
    char tempChar = pinyinString.charAt(0);
    String key;
    if (tempChar < 'a' || tempChar > 'z') {
        key = "#";
    } else {
        key = String.valueOf(tempChar).toUpperCase();

    }
    return key;
}

将无序的Map集合转换为按照字母排序的有序List

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
private List<Map.Entry<String, List<GoodFriendsInfo>>> mGroupingData = new ArrayList<>();
private List<Map.Entry<String, List<GoodFriendsInfo>>> mReserchGroupingData = new ArrayList<>();
/**
 * 分组成Map集合
 */
public void toGropingTypeData(List<GoodFriendsInfo> list) {
    List<GoodFriendsInfo> tempList;
    Map<String, List<GoodFriendsInfo>> tempMap = new HashMap<>();
    for (int i = 0; i < list.size(); i++) {
        GoodFriendsInfo contactsModel1 = list.get(i);
        if(contactsModel1 == null) continue;
        String pinyinString = PinyinHelper.getShortPinyin(
                contactsModel1.getName().toLowerCase().trim());
        contactsModel1.setPyname(pinyinString);
        String key = getPingyingKey(pinyinString);
        if (key == null) continue;
        tempList = tempMap.get(key);
        if(tempList == null){
            tempList = new ArrayList<>();
        }
        tempList.add(contactsModel1);
        tempMap.put(key, tempList);
    }
    Set<Map.Entry<String, List<GoodFriendsInfo>>> setEntry = tempMap.entrySet();
    mGroupingData = new ArrayList<>(setEntry);
    Collections.sort(mGroupingData, new Comparator<Map.Entry<String, List<GoodFriendsInfo>>>() {
        @Override
        public int compare(Map.Entry<String, List<GoodFriendsInfo>> entry1, Map.Entry<String, List<GoodFriendsInfo>> entry2) {
            if(entry1.getKey().equals("#")){
                return 1;
            }else if(entry2.getKey().equals("#")){
                return -1;
            }else{
                Character c1 = entry1.getKey().charAt(0);
                Character c2 = entry2.getKey().charAt(0);
                return c1 - c2;
            }
        }
    });
}

监听输入事件,判断输入文字拼音首字母筛选列表

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
mReserchFriend.addTextChangedListener(new TextWatcher() {

        @Override
        public void beforeTextChanged(CharSequence charSequence, int start, int count, int afte) {

        }

        @Override
        public void onTextChanged(CharSequence charSequence, int start, int before, int count) {
            if(charSequence.length() == 0){
                mResearchPy = "";
                mReserchGroupingData.clear();
                bindview(mGroupingData);
            }else {
                String pinyingStr = PinyinHelper.getShortPinyin(
                        String.valueOf(charSequence).toLowerCase().trim());
                String key = getPingyingKey(pinyingStr);
                if(key == null || mResearchPy.equals(pinyingStr)) return;
                mResearchPy = pinyingStr;
                mReserchGroupingData.clear();
                for (int i = 0; i< mGroupingData.size();i++){
                    if(mGroupingData.get(i).getKey().equals(key)){
                        Map<String, List<GoodFriendsInfo>> searchMap = new HashMap<String, List<GoodFriendsInfo>>();
                        List<GoodFriendsInfo> goodFriendsList = new ArrayList<>(mGroupingData.get(i).getValue());
                        for(int j = goodFriendsList.size() - 1; j >= 0; j--){
                            if(!goodFriendsList.get(j).getPyname().contains(mResearchPy)){
                                goodFriendsList.remove(j);
                            }
                        }
                        searchMap.put(key, goodFriendsList);
                        Set<Map.Entry<String, List<GoodFriendsInfo>>> searchSet = searchMap.entrySet();
                        mReserchGroupingData.add(searchSet.iterator().next());
                        bindview(mReserchGroupingData);
                        break;
                    }
                }
            }
        }

        @Override
        public void afterTextChanged(Editable editable) {

        }
    });
    bindview(mGroupingData);
}

注释:

  1. 上面保存了上次搜索索引(mResearchPy),避免重复搜索。
  2. 注意删除集合中数据要重新创建集合不然会删除原始数据。

全部代码

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
package com.xl.undercover.view.user;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Message;
import android.support.annotation.Nullable;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseExpandableListAdapter;
import android.widget.EditText;
import android.widget.ExpandableListView;
import android.widget.TextView;

import com.xl.undercover.R;
import com.xl.undercover.model.entry.GoodFriendsInfo;
import com.xl.undercover.util.LogUtil;
import com.xl.undercover.view.base.BaseActivity;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import opensource.jpinyin.PinyinHelper;

/**
 * Created by lijiyuan on 2017/2/13.
 * 好友界面,可搜索
 */

public class GoodFriendsActivity extends BaseActivity {

    private String mResearchPy = "";
    private List<GoodFriendsInfo> mGoodFriendsData;
    private ExpandableListView mExpandableListView;
    private List<Map.Entry<String, List<GoodFriendsInfo>>> mGroupingData = new ArrayList<>();
    private List<Map.Entry<String, List<GoodFriendsInfo>>> mReserchGroupingData = new ArrayList<>();

    private EditText mReserchFriend;
    @Override
    protected void handleMessage(Message msg) { }

    @Override
    protected int getContentView() {
        return R.layout.activity_goodfriends;
    }

    @Override
    protected void initView() {
        mExpandableListView = getView(R.id.listview_goodfriends);
        mReserchFriend = getView(R.id.edit_reserch_friend);

        mGoodFriendsData = getData();
        toGropingTypeData(mGoodFriendsData);

        mReserchFriend.addTextChangedListener(new TextWatcher() {

            @Override
            public void beforeTextChanged(CharSequence charSequence, int start, int count, int afte) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int start, int before, int count) {
                if(charSequence.length() == 0){
                    mResearchPy = "";
                    mReserchGroupingData.clear();
                    bindview(mGroupingData);
                }else {
                    String pinyingStr = PinyinHelper.getShortPinyin(
                            String.valueOf(charSequence).toLowerCase().trim());
                    String key = getPingyingKey(pinyingStr);
                    if(key == null || mResearchPy.equals(pinyingStr)) return;
                    mResearchPy = pinyingStr;
                    mReserchGroupingData.clear();
                    for (int i = 0; i< mGroupingData.size();i++){
                        if(mGroupingData.get(i).getKey().equals(key)){
                            Map<String, List<GoodFriendsInfo>> searchMap = new HashMap<String, List<GoodFriendsInfo>>();
                            List<GoodFriendsInfo> goodFriendsList = new ArrayList<>(mGroupingData.get(i).getValue());
                            for(int j = goodFriendsList.size() - 1; j >= 0; j--){
                                if(!goodFriendsList.get(j).getPyname().contains(mResearchPy)){
                                    goodFriendsList.remove(j);
                                }
                            }
                            searchMap.put(key, goodFriendsList);
                            Set<Map.Entry<String, List<GoodFriendsInfo>>> searchSet = searchMap.entrySet();
                            mReserchGroupingData.add(searchSet.iterator().next());
                            bindview(mReserchGroupingData);
                            break;
                        }
                    }
                }
            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });
        bindview(mGroupingData);
    }
    private void bindview(List<Map.Entry<String, List<GoodFriendsInfo>>> mData) {
        mExpandableListView.setAdapter(new GoodFriendsAdapter(mData));
        mExpandableListView.setGroupIndicator(null);
        for (int i = 0; i < mData.size(); i++) {
            mExpandableListView.expandGroup(i);
        }
        mExpandableListView.setOnGroupClickListener(new ExpandableListView.OnGroupClickListener() {
            @Override
            public boolean onGroupClick(ExpandableListView expandableListView, View view, int i, long l) {
                return true;
            }
        });
    }

    @Override
    protected void initData() {

    }

    @Override
    protected void startMine(Context context, Bundle bundle) {

    }

    @Override
    public void turnToOtherView() {

    }


    /**
     * 分组成Map集合
     */
    public void toGropingTypeData(List<GoodFriendsInfo> list) {
        List<GoodFriendsInfo> tempList;
        Map<String, List<GoodFriendsInfo>> tempMap = new HashMap<>();
        for (int i = 0; i < list.size(); i++) {
            GoodFriendsInfo contactsModel1 = list.get(i);
            if(contactsModel1 == null) continue;
            String pinyinString = PinyinHelper.getShortPinyin(
                    contactsModel1.getName().toLowerCase().trim());
            contactsModel1.setPyname(pinyinString);
            String key = getPingyingKey(pinyinString);
            if (key == null) continue;
            tempList = tempMap.get(key);
            if(tempList == null){
                tempList = new ArrayList<>();
            }
            tempList.add(contactsModel1);
            tempMap.put(key, tempList);
        }
        Set<Map.Entry<String, List<GoodFriendsInfo>>> setEntry = tempMap.entrySet();
        mGroupingData = new ArrayList<>(setEntry);
        Collections.sort(mGroupingData, new Comparator<Map.Entry<String, List<GoodFriendsInfo>>>() {
            @Override
            public int compare(Map.Entry<String, List<GoodFriendsInfo>> entry1, Map.Entry<String, List<GoodFriendsInfo>> entry2) {
                if(entry1.getKey().equals("#")){
                    return 1;
                }else if(entry2.getKey().equals("#")){
                    return -1;
                }else{
                    Character c1 = entry1.getKey().charAt(0);
                    Character c2 = entry2.getKey().charAt(0);
                    return c1 - c2;
                }
            }
        });
    }

    @Nullable
    private String getPingyingKey(String pinyinString) {
        //将拼音字符串转换为大写拼音
        if(pinyinString == null && pinyinString.length() == 0) return null;
        //获取大写拼音字符串的第一个字符
        char tempChar = pinyinString.charAt(0);
        String key;
        if (tempChar < 'a' || tempChar > 'z') {
            key = "#";
        } else {
            key = String.valueOf(tempChar).toUpperCase();

        }
        return key;
    }

    /**
     * 初始化数据
     */
    public List<GoodFriendsInfo> getData() {
        List<GoodFriendsInfo> list = new ArrayList<>();
        GoodFriendsInfo contactsModel;
        String[] nameStrings = {"覃", "岑", "$来啊,来互相伤害啊", "疍姬", "梵蒂冈", "亳州",
                "佟", "郄", "张三", "Edward", "李四", "萌萌哒", "霾耷", "离散", "赵信", "啦啦",
                "辣妹子", "嗷嗷", "妹妹", "']asd", "%Hello"};
        for (int i = 0; i < nameStrings.length; i++) {
            contactsModel = new GoodFriendsInfo();
            contactsModel.setName(nameStrings[i]);
            list.add(contactsModel);
        }
        return list;
    }

    class  GoodFriendsAdapter  extends BaseExpandableListAdapter{
        List<Map.Entry<String, List<GoodFriendsInfo>>> mGroupData;
        public GoodFriendsAdapter(List<Map.Entry<String, List<GoodFriendsInfo>>> mData) {
            mGroupData = mData;
        }

        @Override
        public int getGroupCount() {
            return mGroupData.size();
        }

        @Override
        public int getChildrenCount(int i) {
            Map.Entry<String, List<GoodFriendsInfo>> child = mGroupData.get(i);
            if(child == null) return 0;
            return child.getValue().size();
        }

        @Override
        public Object getGroup(int i) {
            return mGroupData.get(i);
        }

        @Override
        public Object getChild(int i, int i1) {
            Map.Entry<String, List<GoodFriendsInfo>> child = mGroupData.get(i);
            if(child == null) return null;
            return child.getValue();
        }

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

        @Override
        public long getChildId(int i, int i1) {
            return i1;
        }

        @Override
        public boolean hasStableIds() {
            return false;
        }

        @Override
        public View getGroupView(int i, boolean b, View view, ViewGroup viewGroup) {
            if (view == null) {
                view = getLayoutInflater().inflate( R.layout.iterm_goodfriends_parent,null);
            }
            TextView text = (TextView) view.findViewById(R.id.text_friend_category);
            text.setText(mGroupData.get(i).getKey());
            return view;
        }

        @Override
        public View getChildView(int i, int i1, boolean b, View view, ViewGroup viewGroup) {
            if (view == null) {
                view = getLayoutInflater().inflate( R.layout.iterm_goodfriends_child,null);
            }
            //ImageView mFriendPic = (ImageView) view.findViewById(R.id.image_friend_picture);
            TextView mFriendname = (TextView) view.findViewById(R.id.text_friend_name);
            //TextView mFriendFollow = (Button) view.findViewById(R.id.btn_friend_follow);
            List<GoodFriendsInfo> entryData = mGroupData.get(i).getValue();
            mFriendname.setText(entryData.get(i1).getName());
            return view;
        }

        @Override
        public boolean isChildSelectable(int i, int i1) {
            return false;
        }
    }

    public static void startActivity(Context context){
        Intent intent = new Intent(context, GoodFriendsActivity.class);
        context.startActivity(intent);
    }

}