您好,登錄后才能下訂單哦!
前言
最近在開發一個IM項目的時候有一個需求就是,好友搜索功能。即在EditText中輸入好友名字,ListView列表中動態展示刷選的好友列表。我把這個功能抽取出來了,先貼一下效果圖:
分析
在查閱資料以后,發現其實Android中已經幫我們實現了這個功能,如果你的ListView使用的是系統的ArrayAdapter,那么恭喜你,下面的事情就很簡單了,你只需要調用下面的代碼就可以實現了:
searchEdittext.addTextChangedListener(new TextWatcher() { @Override public void onTextChanged(CharSequence cs, int arg1, int arg2, int arg3) { // When user change the text mAdapter.getFilter().filter(cs); } @Override public void beforeTextChanged(CharSequence cs, int arg1, int arg2, int arg3) { // } @Override public void afterTextChanged(Editable arg0) { // } });
你沒看錯,就一行 mAdapter.getFilter().filter(cs);便可以實現這個搜索功能。不過我相信大多數Adapter都是自定義的,基于這個需求,我去分析了下ArrayAdapter,發現它實現了Filterable接口,那么接下來的事情就比較簡單了,就讓我們自定的Adapter也去實現Filterable這個接口,不久可以實現這個需求了嗎。下面貼出ArrayAdapter中顯示過濾功能的關鍵代碼:
public class ArrayAdapter<T> extends BaseAdapter implements Filterable { /** * Contains the list of objects that represent the data of this ArrayAdapter. * The content of this list is referred to as "the array" in the documentation. */ private List<T> mObjects; /** * Lock used to modify the content of {@link #mObjects}. Any write operation * performed on the array should be synchronized on this lock. This lock is also * used by the filter (see {@link #getFilter()} to make a synchronized copy of * the original array of data. */ private final Object mLock = new Object(); // A copy of the original mObjects array, initialized from and then used instead as soon as // the mFilter ArrayFilter is used. mObjects will then only contain the filtered values. private ArrayList<T> mOriginalValues; private ArrayFilter mFilter; ... public Filter getFilter() { if (mFilter == null) { mFilter = new ArrayFilter(); } return mFilter; } /** * <p>An array filter constrains the content of the array adapter with * a prefix. Each item that does not start with the supplied prefix * is removed from the list.</p> */ private class ArrayFilter extends Filter { @Override protected FilterResults performFiltering(CharSequence prefix) { FilterResults results = new FilterResults(); if (mOriginalValues == null) { synchronized (mLock) { mOriginalValues = new ArrayList<T>(mObjects); } } if (prefix == null || prefix.length() == 0) { ArrayList<T> list; synchronized (mLock) { list = new ArrayList<T>(mOriginalValues); } results.values = list; results.count = list.size(); } else { String prefixString = prefix.toString().toLowerCase(); ArrayList<T> values; synchronized (mLock) { values = new ArrayList<T>(mOriginalValues); } final int count = values.size(); final ArrayList<T> newValues = new ArrayList<T>(); for (int i = 0; i < count; i++) { final T value = values.get(i); final String valueText = value.toString().toLowerCase(); // First match against the whole, non-splitted value if (valueText.startsWith(prefixString)) { newValues.add(value); } else { final String[] words = valueText.split(" "); final int wordCount = words.length; // Start at index 0, in case valueText starts with space(s) for (int k = 0; k < wordCount; k++) { if (words[k].startsWith(prefixString)) { newValues.add(value); break; } } } } results.values = newValues; results.count = newValues.size(); } return results; } @Override protected void publishResults(CharSequence constraint, FilterResults results) { //noinspection unchecked mObjects = (List<T>) results.values; if (results.count > 0) { notifyDataSetChanged(); } else { notifyDataSetInvalidated(); } } } }
實現
首先寫了一個Model(User)模擬數據
public class User { private int avatarResId; private String name; public User(int avatarResId, String name) { this.avatarResId = avatarResId; this.name = name; } public int getAvatarResId() { return avatarResId; } public void setAvatarResId(int avatarResId) { this.avatarResId = avatarResId; } public String getName() { return name; } public void setName(String name) { this.name = name; } }
自定義一個Adapter(UserAdapter)繼承自BaseAdapter,實現了Filterable接口,Adapter一些常見的處理,我都去掉了,這里主要講講Filterable這個接口。
/** * Contains the list of objects that represent the data of this Adapter. * Adapter數據源 */ private List<User> mDatas; //過濾相關 /** * This lock is also used by the filter * (see {@link #getFilter()} to make a synchronized copy of * the original array of data. * 過濾器上的鎖可以同步復制原始數據。 * */ private final Object mLock = new Object(); // A copy of the original mObjects array, initialized from and then used instead as soon as // the mFilter ArrayFilter is used. mObjects will then only contain the filtered values. //對象數組的備份,當調用ArrayFilter的時候初始化和使用。此時,對象數組只包含已經過濾的數據。 private ArrayList<User> mOriginalValues; private ArrayFilter mFilter; @Override public Filter getFilter() { if (mFilter == null) { mFilter = new ArrayFilter(); } return mFilter; }
寫一個ArrayFilter類繼承自Filter類,我們需要兩個方法:
//執行過濾的方法 protected FilterResults performFiltering(CharSequence prefix);
//得到過濾結果 protected void publishResults(CharSequence prefix, FilterResults results);
貼上完整的代碼,注釋已經寫的不能再詳細了
/** * 過濾數據的類 */ /** * <p>An array filter constrains the content of the array adapter with * a prefix. Each item that does not start with the supplied prefix * is removed from the list.</p> * <p/> * 一個帶有首字母約束的數組過濾器,每一項不是以該首字母開頭的都會被移除該list。 */ private class ArrayFilter extends Filter { //執行刷選 @Override protected FilterResults performFiltering(CharSequence prefix) { FilterResults results = new FilterResults();//過濾的結果 //原始數據備份為空時,上鎖,同步復制原始數據 if (mOriginalValues == null) { synchronized (mLock) { mOriginalValues = new ArrayList<>(mDatas); } } //當首字母為空時 if (prefix == null || prefix.length() == 0) { ArrayList<User> list; synchronized (mLock) {//同步復制一個原始備份數據 list = new ArrayList<>(mOriginalValues); } results.values = list; results.count = list.size();//此時返回的results就是原始的數據,不進行過濾 } else { String prefixString = prefix.toString().toLowerCase();//轉化為小寫 ArrayList<User> values; synchronized (mLock) {//同步復制一個原始備份數據 values = new ArrayList<>(mOriginalValues); } final int count = values.size(); final ArrayList<User> newValues = new ArrayList<>(); for (int i = 0; i < count; i++) { final User value = values.get(i);//從List<User>中拿到User對象 // final String valueText = value.toString().toLowerCase(); final String valueText = value.getName().toString().toLowerCase();//User對象的name屬性作為過濾的參數 // First match against the whole, non-splitted value if (valueText.startsWith(prefixString) || valueText.indexOf(prefixString.toString()) != -1) {//第一個字符是否匹配 newValues.add(value);//將這個item加入到數組對象中 } else {//處理首字符是空格 final String[] words = valueText.split(" "); final int wordCount = words.length; // Start at index 0, in case valueText starts with space(s) for (int k = 0; k < wordCount; k++) { if (words[k].startsWith(prefixString)) {//一旦找到匹配的就break,跳出for循環 newValues.add(value); break; } } } } results.values = newValues;//此時的results就是過濾后的List<User>數組 results.count = newValues.size(); } return results; } //刷選結果 @Override protected void publishResults(CharSequence prefix, FilterResults results) { //noinspection unchecked mDatas = (List<User>) results.values;//此時,Adapter數據源就是過濾后的Results if (results.count > 0) { notifyDataSetChanged();//這個相當于從mDatas中刪除了一些數據,只是數據的變化,故使用notifyDataSetChanged() } else { /** * 數據容器變化 ----> notifyDataSetInValidated 容器中的數據變化 ----> notifyDataSetChanged */ notifyDataSetInvalidated();//當results.count<=0時,此時數據源就是重新new出來的,說明原始的數據源已經失效了 } } }
特別說明
//User對象的name屬性作為過濾的參數 final String valueText = value.getName().toString().toLowerCase();
這個地方是,你要進行搜索的關鍵字,比如我這里使用的是User對象的Name屬性,就是把用戶名當作關鍵字來進行過濾篩選的。這里要根據你自己的具體邏輯來進行設置。
在這里進行關鍵字匹配,如果你只想使用第一個字符匹配,那么你只需要使用這行代碼就可以了:
//首字符匹配 valueText.startsWith(prefixString)
如果你的需求是只要輸入的字符出現在ListView列表中,那么該item就要顯示出來,那么你就需要這行代碼了:
//你輸入的關鍵字包含在了某個item中,位置不做考慮,即可以不是第一個字符 valueText.indexOf(prefixString.toString()) != -1
這樣就完成了一個EditText + ListView實現搜索的功能。我在demo中用兩種方法實現了這一效果。第一種是系統的ArrayAdapter實現,第二種是自定義Adapter實現。
demo下載地址:EditSearch_jb51.rar
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持億速云。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。