我正在尝试将搜索功能添加到具有自定义适配器的 ListView 中。当我在 EditText 中输入内容时,它会搜索并正确显示结果,但如果我尝试删除我刚刚写的内容,它不会出现在初始列表中,它将保留在已过滤的列表中。这是代码:
在 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;
}
我的代码有什么问题?谢谢!