我試圖將搜索功能添加到具有自定義適配器的ListView。當我在EditText中鍵入某些內容時,它會正確地搜索並顯示結果,但如果我試圖擦除剛剛寫入的內容,它將不會與初始列表一起顯示,它將保留在已經過濾的列表中。 下面是代碼:在ListView中的Android搜索無法正常工作
在MainActivity:
private TextWatcher searchTextWatcher = new TextWatcher() {
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
adapter.getFilter().filter(s.toString());
adapter.notifyDataSetChanged();
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void afterTextChanged(Editable s) {
}
};
在LazyAdapter:
public Filter getFilter() {
return new Filter() {
@SuppressWarnings("unchecked")
@Override
protected void publishResults(CharSequence constraint, FilterResults results) {
data = (ArrayList<HashMap<String, String>>) results.values;
LazyAdapter.this.notifyDataSetChanged();
}
@Override
protected FilterResults performFiltering(CharSequence constraint) {
ArrayList<HashMap<String, String>> filteredResults = getFilteredResults(constraint);
FilterResults results = new FilterResults();
results.values = filteredResults;
return results;
}
};
}
protected ArrayList<HashMap<String, String>> getFilteredResults(
CharSequence constraint) {
ArrayList<HashMap<String, String>> filteredTeams = new ArrayList<HashMap<String, String>>();
for(int i=0;i< data.size();i++){
if(data.get(i).get(MainActivity.KEY_TITLE).toLowerCase().startsWith(constraint.toString().toLowerCase())){
filteredTeams.add(data.get(i));
}
}
return filteredTeams;
}
什麼是錯我的代碼? 謝謝!
http://stackoverflow.com/questions/13090046/how-to-implement-search-in-customlistview-based-on-class-item-of-pojo-class-in-a。檢查這是否有幫助 – Raghunandan