在查閱資料以后,發(fā)現(xiàn)其實Android中已經(jīng)幫我們實現(xiàn)了這個功能,如果你的ListView使用的是系統(tǒng)的ArrayAdapter抚恒,那么恭喜你,下面的事情就很簡單了络拌,你只需要調(diào)用下面的代碼就可以實現(xiàn)了:
<pre class="brush:java;">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) {
//
}
});
</pre>
你沒看錯俭驮,就一行 mAdapter.getFilter().filter(cs);便可以實現(xiàn)這個搜索功能。不過我相信大多數(shù)Adapter都是自定義的春贸,基于這個需求混萝,我去分析了下ArrayAdapter,發(fā)現(xiàn)它實現(xiàn)了Filterable接口祥诽,那么接下來的事情就比較簡單了譬圣,就讓我們自定的Adapter也去實現(xiàn)Filterable這個接口,不久可以實現(xiàn)這個需求了嗎雄坪。下面貼出ArrayAdapter中顯示過濾功能的關(guān)鍵代碼:
<pre class="brush:java;">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();
}
}
}
}
</pre>
實現(xiàn)
首先寫了一個Model(User)模擬數(shù)據(jù)
<pre class="brush:java;">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;
}
}
</pre>
自定義一個Adapter(UserAdapter)繼承自BaseAdapter厘熟,實現(xiàn)了Filterable接口,Adapter一些常見的處理维哈,我都去掉了绳姨,這里主要講講Filterable這個接口。
<pre class="brush:java;">/**
- Contains the list of objects that represent the data of this Adapter.
- Adapter數(shù)據(jù)源
*/
private List<User> mDatas;
//過濾相關(guān)
/**
- This lock is also used by the filter
- (see {@link #getFilter()} to make a synchronized copy of
- the original array of data.
- 過濾器上的鎖可以同步復(fù)制原始數(shù)據(jù)阔挠。
*/
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.
//對象數(shù)組的備份飘庄,當(dāng)調(diào)用ArrayFilter的時候初始化和使用。此時购撼,對象數(shù)組只包含已經(jīng)過濾的數(shù)據(jù)跪削。
private ArrayList<User> mOriginalValues;
private ArrayFilter mFilter;
@Override
public Filter getFilter() {
if (mFilter == null) {
mFilter = new ArrayFilter();
}
return mFilter;
}
</pre>
寫一個ArrayFilter類繼承自Filter類谴仙,我們需要兩個方法:
<pre class="brush:java;">//執(zhí)行過濾的方法
protected FilterResults performFiltering(CharSequence prefix);</pre>
<pre class="brush:java;">//得到過濾結(jié)果
protected void publishResults(CharSequence prefix, FilterResults results);</pre>
貼上完整的代碼,注釋已經(jīng)寫的不能再詳細(xì)了
<pre class="brush:java;"> /**
過濾數(shù)據(jù)的類
/
/*<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/>
-
一個帶有首字母約束的數(shù)組過濾器碾盐,每一項不是以該首字母開頭的都會被移除該list晃跺。
*/
private class ArrayFilter extends Filter {
//執(zhí)行刷選
@Override
protected FilterResults performFiltering(CharSequence prefix) {
FilterResults results = new FilterResults();//過濾的結(jié)果
//原始數(shù)據(jù)備份為空時,上鎖毫玖,同步復(fù)制原始數(shù)據(jù)
if (mOriginalValues == null) {
synchronized (mLock) {
mOriginalValues = new ArrayList<>(mDatas);
}
}
//當(dāng)首字母為空時
if (prefix == null || prefix.length() == 0) {
ArrayList<User> list;
synchronized (mLock) {//同步復(fù)制一個原始備份數(shù)據(jù)
list = new ArrayList<>(mOriginalValues);
}
results.values = list;
results.count = list.size();//此時返回的results就是原始的數(shù)據(jù)掀虎,不進(jìn)行過濾
} else {
String prefixString = prefix.toString().toLowerCase();//轉(zhuǎn)化為小寫ArrayList<User> values;
synchronized (mLock) {//同步復(fù)制一個原始備份數(shù)據(jù)
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屬性作為過濾的參數(shù)
// First match against the whole, non-splitted value
if (valueText.startsWith(prefixString) || valueText.indexOf(prefixString.toString()) != -1) {//第一個字符是否匹配
newValues.add(value);//將這個item加入到數(shù)組對象中
} 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循環(huán) newValues.add(value); break; } } }
}
results.values = newValues;//此時的results就是過濾后的List<User>數(shù)組
results.count = newValues.size();
}
return results;
}
//刷選結(jié)果
@Override
protected void publishResults(CharSequence prefix, FilterResults results) {
//noinspection unchecked
mDatas = (List<User>) results.values;//此時付枫,Adapter數(shù)據(jù)源就是過濾后的Results
if (results.count > 0) {
notifyDataSetChanged();//這個相當(dāng)于從mDatas中刪除了一些數(shù)據(jù)烹玉,只是數(shù)據(jù)的變化,故使用notifyDataSetChanged()
} else {
/**
* 數(shù)據(jù)容器變化 ----> notifyDataSetInValidated
容器中的數(shù)據(jù)變化 ----> notifyDataSetChanged
*/
notifyDataSetInvalidated();//當(dāng)results.count<=0時阐滩,此時數(shù)據(jù)源就是重新new出來的二打,說明原始的數(shù)據(jù)源已經(jīng)失效了
}
}
}
</pre>
特別說明
<pre class="brush:java;">//User對象的name屬性作為過濾的參數(shù)
final String valueText = value.getName().toString().toLowerCase();</pre>
這個地方是,你要進(jìn)行搜索的關(guān)鍵字叶眉,比如我這里使用的是User對象的Name屬性址儒,就是把用戶名當(dāng)作關(guān)鍵字來進(jìn)行過濾篩選的。這里要根據(jù)你自己的具體邏輯來進(jìn)行設(shè)置衅疙。
<a onclick="doCopy('code18366')" id="copybut18366" class="copybut" style="CURSOR: pointer" data="18366"><u>復(fù)制代碼</u></a>
代碼如下:
if (valueText.startsWith(prefixString) || valueText.indexOf(prefixString.toString()) != -1)
在這里進(jìn)行關(guān)鍵字匹配莲趣,如果你只想使用第一個字符匹配,那么你只需要使用這行代碼就可以了:
<pre class="brush:java;">//首字符匹配
valueText.startsWith(prefixString)</pre>
如果你的需求是只要輸入的字符出現(xiàn)在ListView列表中饱溢,那么該item就要顯示出來喧伞,那么你就需要這行代碼了:
<pre class="brush:java;">//你輸入的關(guān)鍵字包含在了某個item中,位置不做考慮绩郎,即可以不是第一個字符
valueText.indexOf(prefixString.toString()) != -1</pre>
這樣就完成了一個EditText + ListView實現(xiàn)搜索的功能潘鲫。