实例介绍
【实例简介】获取手机电话本并支持拼音模糊搜索关键字
【实例截图】
【核心代码】
package com.example; import java.util.ArrayList; import java.util.List; import java.util.regex.Pattern; import net.sourceforge.pinyin4j.PinyinHelper; import net.sourceforge.pinyin4j.format.HanyuPinyinCaseType; import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat; import net.sourceforge.pinyin4j.format.HanyuPinyinToneType; import net.sourceforge.pinyin4j.format.HanyuPinyinVCharType; import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination; import android.app.Activity; import android.content.Context; import android.content.res.Resources; import android.database.Cursor; import android.graphics.Bitmap; import android.os.Bundle; import android.provider.ContactsContract.CommonDataKinds.Phone; import android.text.Editable; import android.text.TextWatcher; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.inputmethod.InputMethodManager; import android.widget.AbsListView; import android.widget.BaseAdapter; import android.widget.EditText; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.ListView; import android.widget.ProgressBar; import android.widget.TextView; public class PinYinSearchActivity extends Activity { /** Called when the activity is first created. */ static String[] pinyin = { "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" }; public List<PersonInfo> contactList = null; public List<PersonInfo> searchList = null; EditText editSearch; TextView loadingPrompt; ImageView btnClearSearch; ProgressBar loadingBar; ListView listView; PYListAdapter adapter; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); searchList = new ArrayList<PersonInfo>(); contactList = new ArrayList<PersonInfo>(); editSearch = (EditText) findViewById(R.id.edit_search); btnClearSearch = (ImageView) findViewById(R.id.btn_clean_search); btnClearSearch.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { // TODO Auto-generated method stub System.out.println("ffffffffffffffff==>" toPinYin(editSearch.getText().toString())); editSearch.setText(""); btnClearSearch.setVisibility(View.GONE); adapter.list = contactList; updateSearchHint(); adapter.isShowNum = false; adapter.notifyDataSetChanged(); listView.invalidate(); } }); editSearch.addTextChangedListener(new TextWatcher() { public void onTextChanged(CharSequence s, int start, int before, int count) { // TODO Auto-generated method stub // Log.i("text changed", "start=" start "before" before); if (s.length() != 0) { btnClearSearch.setVisibility(View.VISIBLE); getSearchUser(s.toString()); adapter.list = searchList; adapter.isShowNum = true; } else { btnClearSearch.setVisibility(View.GONE); adapter.list = contactList; adapter.isShowNum = false; } updateSearchHint(); adapter.notifyDataSetChanged(); listView.invalidate(); } public void beforeTextChanged(CharSequence s, int start, int count, int after) { // TODO Auto-generated method stub //Log.i("before text changed", "start=" start ); } public void afterTextChanged(Editable s) { // TODO Auto-generated method stub } }); loadingPrompt = (TextView) findViewById(R.id.loadingPrompt); loadingBar = (ProgressBar) findViewById(R.id.loadingBar); listView = (ListView) findViewById(R.id.listView); setContactList(); adapter = new PYListAdapter(PinYinSearchActivity.this, contactList); listView.setAdapter(adapter); listView.setOnScrollListener(new AbsListView.OnScrollListener() { public void onScrollStateChanged(AbsListView view, int scrollState) { // TODO Auto-generated method stub InputMethodManager inputMethodManager = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE); inputMethodManager.hideSoftInputFromWindow(PinYinSearchActivity.this.getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS); } public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) { // TODO Auto-generated method stub } }); } public void updateSearchHint(){ Resources res = getResources(); String text = String.format(res.getString(R.string.contact_search_hint_text), adapter.list.size()); editSearch.setHint(text); } private void getSearchUser(String condition ) { searchList.clear(); if (condition == null || condition.equals("")) return ; String[] projection= {Phone.DISPLAY_NAME, Phone.NUMBER, Phone.PHOTO_ID, "sort_key"}; String selection = Phone.NUMBER " like '%" condition "%' or " Phone.DISPLAY_NAME " like '%" condition "%' or " "sort_key" " like '%" getPYSearchRegExp(condition, "%") "%'"; Cursor cur = getContentResolver().query(Phone.CONTENT_URI, projection, selection, null, Phone.DISPLAY_NAME " COLLATE LOCALIZED ASC"); cur.moveToFirst(); while(cur.getCount() > cur.getPosition()) { PersonInfo person = new PersonInfo(PinYinSearchActivity.this); List<String> phoneList = new ArrayList<String>(); String number = cur.getString(cur.getColumnIndex(Phone.NUMBER)); String name = cur.getString(cur.getColumnIndex(Phone.DISPLAY_NAME)); String photo_id = cur.getString(cur.getColumnIndex(Phone.PHOTO_ID)); String sort_key = cur.getString(cur.getColumnIndex("sort_key")); Log.i("contacts>>>", "name:" name "number:" number "photo:" photo_id "sort_key" sort_key); boolean show = true; System.out.println("isPinYin====>" isPinYin(condition) ); if (isPinYin(condition) ) { System.out.println("containCn====>" sort_key); if(containCn(sort_key)) { show = pyMatches(sort_key, condition.replaceAll(" ", "")); } else { if (name != null && name.startsWith(condition)) //如果sort_key 不包含中文 则需要用display_name匹配 英文匹配采取前缀匹配 show = true; else show = false; } } System.out.println("is show " show); if (show) { person.setName(name); person.setSortKey(sort_key); person.setPhotoId(photo_id); phoneList.add(number); person.setPhone(phoneList); add2List(searchList, person); } cur.moveToNext(); } cur.close(); } /** * 获取通讯录列表 */ private void setContactList() { String[] projection= {Phone.DISPLAY_NAME, Phone.NUMBER, Phone.PHOTO_ID}; Cursor cur = getContentResolver().query(Phone.CONTENT_URI, projection, null, null, Phone.DISPLAY_NAME " COLLATE LOCALIZED ASC"); cur.moveToFirst(); while(cur.getCount() > cur.getPosition()) { PersonInfo person = new PersonInfo(PinYinSearchActivity.this); List<String> phone = new ArrayList<String>(); String number = cur.getString(cur.getColumnIndex(Phone.NUMBER)); String name = cur.getString(cur.getColumnIndex(Phone.DISPLAY_NAME)); String photo_id = cur.getString(cur.getColumnIndex(Phone.PHOTO_ID)); Log.i("contacts>>>", "name:" name "number:" number "photo:" photo_id); person.setName(name); person.setPhotoId(photo_id); phone.add(number); person.setPhone(phone); add2List(contactList, person); cur.moveToNext(); } cur.close(); } public void add2List(List<PersonInfo> list , PersonInfo person) { for(int i = 0; i < list.size(); i) { if(list.get(i).getName().equals(person.getName())) { for(int k = 0; k < person.getPhone().size(); k) list.get(i).addPhone(person.getPhone().get(k)); return ; } } list.add(person); } /** * * @param str 搜索字符串 * @param exp 追加的正则表达式 * @return 拼音搜索正则表达式 */ public String getPYSearchRegExp(String str, String exp) { int start = 0; String regExp = ""; str = str.toLowerCase(); boolean isFirstSpell = true; for (int i = 0; i < str.length(); i) { String tmp = str.substring(start, i 1); isFirstSpell = binSearch(tmp) ? false : true; if (isFirstSpell) { regExp = str.substring(start, i) exp; start = i; } else { isFirstSpell = true; } if (i == str.length() - 1) regExp = str.substring(start, i 1) exp; } System.out.println("regExp============>" regExp); return regExp; } /** * 2分法查找拼音列表 * @param str 拼音字符串 * @return 是否是存在于拼音列表 */ public boolean binSearch(String str) { int mid = 0; int start = 0; int end = pinyin.length - 1; while (start < end) { mid = start ((end - start) / 2 ); if (pinyin[mid].matches(str "[a-zA-Z]*")) return true; if (pinyin[mid].compareTo(str) < 0) start = mid 1; else end = mid - 1; } return false; } /** * 拼音匹配 * @param src 含有中文的字符串 * @param des 查询的拼音 * @return 是否能匹配拼音 */ public boolean pyMatches(String src, String des) { System.out.println("stc===>" src); System.out.println("des===>" des); if (src != null) { src = src.replaceAll("[^ a-zA-Z]", "").toLowerCase(); src = src.replaceAll("[ ] ", " "); System.out.println("src===>" src); String condition = getPYSearchRegExp(des, "[a-zA-Z]* "); /* r[a-zA-Z]* y[a-zA-Z]* Pattern pattern = Pattern.compile(condition); Matcher m = pattern.matcher(src); return m.find(); */ String[] tmp = condition.split("[ ]"); String[] tmp1 = src.split("[ ]"); for (int i = 0; i < tmp.length; i ) { System.out.println("tmp==>" tmp[i]); } for (int i = 0; i < tmp1.length; i ) { System.out.println("tmp1==>" tmp1[i]); } for(int i = 0; i tmp.length <= tmp1.length; i) { String str = ""; for (int j = 0; j < tmp.length; j ) str = tmp1[i j] " "; System.out.println("str==>" str); if (str.matches(condition)) return true; } } return false; } public boolean isNumeric(String str) { Pattern pattern = Pattern.compile("[0-9]*"); return pattern.matcher(str).matches(); } public boolean isPinYin(String str) { Pattern pattern = Pattern.compile("[ a-zA-Z]*"); return pattern.matcher(str).matches(); } public boolean containCn(String str) { Pattern pattern = Pattern.compile("[\\u4e00-\\u9fa5]"); return pattern.matcher(str).find(); /* while (m.find()) { for (int i = 0; i <= m.groupCount(); i ) { count = count 1; } } System.out.println("共有 " count "个 "); */ } public class PYListAdapter extends BaseAdapter { List<PersonInfo> list; private Context context; public boolean isShowNum = false; public PYListAdapter(Context context, List<PersonInfo> list) { this.context = context; this.list = list; } public int getCount() { // TODO Auto-generated method stub return list.size(); } public Object getItem(int arg0) { // TODO Auto-generated method stub return arg0; } public long getItemId(int position) { // TODO Auto-generated method stub return position; } public View getView(int position, View convertView, ViewGroup parent) { // TODO Auto-generated method stub if(list.size() == 0) return null; LayoutInflater inflater = LayoutInflater.from(context); LinearLayout layout=(LinearLayout) inflater.inflate(R.layout.list_item, null); PersonInfo person = list.get(position); ImageView image = (ImageView) layout.findViewById(R.id.itemImage); Bitmap bitmap = person.getPhoto(); if (bitmap != null) image.setImageBitmap(bitmap); TextView textName=(TextView) layout.findViewById(R.id.itemText); textName.setText(person.getName()); if (isShowNum) { TextView textNum= (TextView) layout.findViewById(R.id.itemText1); textNum.setVisibility(View.VISIBLE); textNum.setText(person.getPhone().get(0)); } return layout; } } public static String toPinYin(String hanzhis){ CharSequence s= hanzhis; char [] hanzhi=new char[s.length()]; for(int i=0;i<s.length();i ){ hanzhi[i]=s.charAt(i); } char [] t1 =hanzhi; String[] t2 = new String[s.length()]; /** *//** * 设置输出格式 */ net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat t3 = new HanyuPinyinOutputFormat(); t3.setCaseType(HanyuPinyinCaseType.UPPERCASE); t3.setToneType(HanyuPinyinToneType.WITHOUT_TONE); t3.setVCharType(HanyuPinyinVCharType.WITH_V); int t0=t1.length; String py = ""; try { for (int i=0;i<t0;i ) { if (((t1[i]>='a')&&(t1[i] <='z'))||((t1[i]>='A')&&(t1[i]<='Z'))||((t1[i]>='0')&&(t1[i]<='9'))) { py=py t1[i]; }else { t2 = PinyinHelper.toHanyuPinyinStringArray(t1[i], t3); py=py t2[0].toString(); } } } catch (BadHanyuPinyinOutputFormatCombination e1) { e1.printStackTrace(); } return py.trim(); } }
小贴士
感谢您为本站写下的评论,您的评论对其它用户来说具有重要的参考价值,所以请认真填写。
- 类似“顶”、“沙发”之类没有营养的文字,对勤劳贡献的楼主来说是令人沮丧的反馈信息。
- 相信您也不想看到一排文字/表情墙,所以请不要反馈意义不大的重复字符,也请尽量不要纯表情的回复。
- 提问之前请再仔细看一遍楼主的说明,或许是您遗漏了。
- 请勿到处挖坑绊人、招贴广告。既占空间让人厌烦,又没人会搭理,于人于己都无利。
关于好例子网
本站旨在为广大IT学习爱好者提供一个非营利性互相学习交流分享平台。本站所有资源都可以被免费获取学习研究。本站资源来自网友分享,对搜索内容的合法性不具有预见性、识别性、控制性,仅供学习研究,请务必在下载后24小时内给予删除,不得用于其他任何用途,否则后果自负。基于互联网的特殊性,平台无法对用户传输的作品、信息、内容的权属或合法性、安全性、合规性、真实性、科学性、完整权、有效性等进行实质审查;无论平台是否已进行审查,用户均应自行承担因其传输的作品、信息、内容而可能或已经产生的侵权或权属纠纷等法律责任。本站所有资源不代表本站的观点或立场,基于网友分享,根据中国法律《信息网络传播权保护条例》第二十二与二十三条之规定,若资源存在侵权或相关问题请联系本站客服人员,点此联系我们。关于更多版权及免责申明参见 版权及免责申明
网友评论
我要评论