使用EditText对ListView进行过滤,并作拼音匹配

 

使用EditText对ListView进行过滤,并作拼音匹配

分类: android   85人阅读  评论(0)  收藏  举报

通过EditText中的输入,实现ListView过滤,主要是让adapter实现Filterable接口。可以参考SimpleAdapter的实现方式。

至于拼音过滤,在google code中有一个pinyin4android的开源项目,已经实现了对中文拼音的匹配。

效果图:


定义一个UserAdapter,对user的name字段进行过滤:

[html]  view plain copy
  1. public class UserAdapter extends BaseAdapter implements Filterable{  
  2.         private List<User> users;  
  3.         public Context mContext;  
  4.         private LayoutInflater mInflater;  
  5.         private FilterDemo mFilter;  
  6.         private ArrayList<User> mDisplayData;  
  7.         //记录索引  
  8.         private ArrayList<FilterIndex> mFilterIndexs;  
  9.           
  10.         public UserAdapter(Context context, List<User> users)  
  11.         {  
  12.             super();  
  13.               
  14.             mContext = context;  
  15.               
  16.             this.users = users;  
  17.               
  18.             mDisplayData = (ArrayList<User>) users;  
  19.               
  20.             mFilterIndexs = new ArrayList<FilterIndex>();  
  21.             mInflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);  
  22.         }  
  23.           
  24.         @Override  
  25.         public int getCount()  
  26.         {  
  27.             // TODO Auto-generated method stub  
  28.             return mDisplayData.size();  
  29.         }  
  30.   
  31.         @Override  
  32.         public Object getItem(int position)  
  33.         {  
  34.             // TODO Auto-generated method stub  
  35.               
  36.             return mDisplayData.get(position);  
  37.         }  
  38.   
  39.         @Override  
  40.         public long getItemId(int position)  
  41.         {  
  42.             // TODO Auto-generated method stub  
  43.             return mDisplayData.get(position).getId();  
  44.         }  
  45.   
  46.         @Override  
  47.         public View getView(final int position, View convertView, ViewGroup parent)  
  48.         {  
  49.             // TODO Auto-generated method stub  
  50.   
  51.             if (convertView == null)  
  52.               convertView = mInflater.inflate(R.layout.item, null);  
  53.               
  54.             ViewHolder holder = new ViewHolder();  
  55.             holder.name = (TextView) convertView.findViewById(R.id.name);   
  56.             holder.age = (TextView) convertView.findViewById(R.id.age);  
  57.               
  58.             User user = mDisplayData.get(position);  
  59.               
  60.             SpannableStringBuilder ss=new SpannableStringBuilder(user.getName());  
  61.             if(!mFilterIndexs.isEmpty())  
  62.               ss.setSpan(new ForegroundColorSpan(Color.RED),mFilterIndexs.get(position).getBegin(),mFilterIndexs.get(position).getEnd(),Spannable.SPAN_EXCLUSIVE_INCLUSIVE);  
  63.                 
  64.             holder.name.setText(ss);  
  65.             holder.age.setText(user.getAge()+"");  
  66.   
  67.             return convertView;  
  68.   
  69.         }  
  70.           
  71.           
  72.         static class ViewHolder  
  73.         {  
  74.             TextView name;  
  75.             TextView age;  
  76.               
  77.         }  
  78.   
  79.         @Override  
  80.         public Filter getFilter()  
  81.         {  
  82.             // TODO Auto-generated method stub  
  83.             if (mFilter == null) {  
  84.                 mFilter = new FilterDemo();  
  85.             }  
  86.             return mFilter;  
  87.         }  
  88.         private class FilterDemo extends Filter {  
  89.   
  90.             @Override  
  91.             protected FilterResults performFiltering(CharSequence prefix) {  
  92.                 FilterResults results = new FilterResults();  
  93.                   
  94.                 ArrayList<String> mData = new ArrayList<String>();  
  95.                   
  96.                 mFilterIndexs.clear();  
  97.                  
  98.                 for(int i = 0; i < users.size(); i ++){  
  99.                         String name = users.get(i).getName();  
  100.                         mData.add(name);  
  101.                 }  
  102.                  
  103.                 if (prefix == null || prefix.length() == 0) {  
  104.                   
  105.                     results.values = mData;  
  106.                     results.count = mData.size();  
  107.                   
  108.                 } else {  
  109.                     String prefixString = prefix.toString();  
  110.                       
  111.                     int count = mData.size();  
  112.   
  113.                     ArrayList<String> newValues = new ArrayList<String>(count);  
  114.                       
  115.                     for (int j = 0; j < count; j++) {  
  116.            
  117.                          String s = mData.get(j);  
  118.                           
  119.                         //  
  120.                         String s1 = getPinYinHeadChar(s);  
  121.                            
  122.                         if(s1.contains(prefixString))  
  123.                         {  
  124.                              getFilterIndex(s1,prefixString);  
  125.                              newValues.add(s);  
  126.                          }else  
  127.                          if(s.contains(prefixString))  
  128.                         {  
  129.                              getFilterIndex(s,prefixString);  
  130.                              newValues.add(s);  
  131.                         }  
  132.                             
  133.                     }  
  134.                    
  135.                     results.values = newValues;  
  136.                     results.count = newValues.size();  
  137.                 }  
  138.                   
  139.                 return results;  
  140.             }  
  141.             @SuppressWarnings("unchecked")  
  142.             @Override  
  143.             protected void publishResults(CharSequence constraint, FilterResults results) {  
  144.               
  145.                     mDisplayData = new ArrayList<User>(results.count);  
  146.                       
  147.                     for(String username:(ArrayList<String>)results.values)  
  148.                     {  
  149.                           for(User userInfo:users)  
  150.                           {  
  151.                               if(userInfo.getName().equals(username)){  
  152.                                     
  153.                                   mDisplayData.add(userInfo);  
  154.                               }  
  155.                           }  
  156.                     }  
  157.                       
  158.                     notifyDataSetChanged();  
  159.                
  160.             }  
  161.               
  162.           //提取汉字的首字母  
  163.             private String getPinYinHeadChar(String str) {  
  164.                StringBuilder convert = new StringBuilder();  
  165.                int length = str.length();  
  166.                for (int j = 0; j < length; j++) {  
  167.                    char word = str.charAt(j);  
  168.                     try {  
  169.                           
  170.                         String pinyinArray = PinyinUtil.toPinyin(mContext, word);  
  171.                           
  172.                         if (pinyinArray != null) {  
  173.                             convert.append(pinyinArray.charAt(0));  
  174.                         } else {  
  175.                             convert.append(word);  
  176.                         }  
  177.                           
  178.                     } catch (Exception e) {  
  179.                         e.printStackTrace();  
  180.                     }  
  181.                     
  182.                }  
  183.   
  184.                return convert.toString();  
  185.            }  
  186.              
  187.             /**  
  188.              * 获取指定字符的开始与结束的位置  
  189.              */  
  190.            private void getFilterIndex(String father,String child)  
  191.            {  
  192.                int start = father.indexOf(child);  
  193.                int end = start+child.length();  
  194.                FilterIndex filterIndex = new FilterIndex(start,end);  
  195.                mFilterIndexs.add(filterIndex);  
  196.                  
  197.            }  
  198.              
  199.     }  
  200.            class FilterIndex  
  201.            {  
  202.                private int begin;  
  203.                private int end;  
  204.                  
  205.                public FilterIndex(int begin,int end)  
  206.                {  
  207.                    this.begin = begin;  
  208.                    this.end = end;  
  209.                }  
  210.   
  211.             public int getBegin() {  
  212.                 return begin;  
  213.             }  
  214.   
  215.             public void setBegin(int begin) {  
  216.                 this.begin = begin;  
  217.             }  
  218.   
  219.             public int getEnd() {  
  220.                 return end;  
  221.             }  
  222.   
  223.             public void setEnd(int end) {  
  224.                 this.end = end;  
  225.             }  
  226.                  
  227.            }  
  228.     }  


 然后再Activity中使用该adapter,为EditText添加addTextChangedListener: 
 

[html]  view plain copy
  1. private ListView mListView;  
  2.     @Override  
  3.     public void onCreate(Bundle savedInstanceState) {  
  4.         super.onCreate(savedInstanceState);  
  5.         setContentView(R.layout.main);  
  6.         initComponent();  
  7.     }  
  8.     private void initComponent() {  
  9.         // TODO Auto-generated method stub  
  10.         EditText edit = (EditText) findViewById(R.id.edit);  
  11.         mListView = (ListView) findViewById(R.id.list_view);  
  12.         List<User> users = new ArrayList<User>();  
  13.         users.add(0, new User("zhangsan", 20));  
  14.         users.add(1, new User("lishi", 21));  
  15.         users.add(1, new User("wangwu", 21));  
  16.         users.add(1, new User("zhaoliu", 21));  
  17.         users.add(1, new User("xiaoming", 21));  
  18.         users.add(1, new User("daming", 21));  
  19.         final UserAdapter adapter = new UserAdapter(this, users);  
  20.         mListView.setAdapter(adapter);  
  21.         edit.addTextChangedListener(new TextWatcher() {  
  22.               
  23.             @Override  
  24.             public void onTextChanged(CharSequence s, int start, int before, int count) {  
  25.                 // TODO Auto-generated method stub  
  26.                   
  27.             }  
  28.               
  29.             @Override  
  30.             public void beforeTextChanged(CharSequence s, int start, int count,  
  31.                     int after) {  
  32.                 // TODO Auto-generated method stub  
  33.                   
  34.             }  
  35.               
  36.             @Override  
  37.             public void afterTextChanged(Editable s) {  
  38.                 // TODO Auto-generated method stub  
  39.                 adapter.getFilter().filter(s);  
  40.             }  
  41.         });  
  42.     }  
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值