我实现了一个AutoCompleteTextView,其中数据在用户输入新文本时从服务器更新。它工作得很好。然而,每次我输入新的查询时,都会显示先前的结果,直到新的结果集被更新。
我猜测它会显示当前查询的结果,直到后端响应新的搜索结果。有没有一种方法可以清除当前的结果?
活动代码:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_search_test);
actv = (AutoCompleteTextView) findViewById(R.id.actv);
actv.setThreshold(1);
actv.setAdapter(new SearchSuggestionsAdapter(this, actv.getText().toString()));
自定义适配器:
public class SearchSuggestionsAdapter extends ArrayAdapter<String> {
List<String> types = new ArrayList<>();
protected static final String TAG = "SuggestionAdapter";
private List<String> suggestions;
private Context context;
public SearchSuggestionsAdapter(Activity context, String nameFilter) {
super(context, android.R.layout.simple_dropdown_item_1line);
suggestions = new ArrayList<String>();
this.context = context;
}
@Override
public int getCount() {
return suggestions.size();
}
@Override
public String getItem(int index) {
return suggestions.get(index);
}
@Override
public Filter getFilter() {
Filter myFilter = new Filter() {
@Override
protected FilterResults performFiltering(CharSequence constraint) {
FilterResults filterResults = new FilterResults();
if (constraint != null) {
//Get new results from backend
//searchItemsFromServer is the method that returns the data
//new data is successfully sent. no problem there
List<String> new_suggestions = searchItemsFromServer(constraint.toString());
suggestions.clear();
for (int i = 0; i < new_suggestions.size(); i++) {
suggestions.add(new_suggestions.get(i));
}
filterResults.values = suggestions;
filterResults.count = suggestions.size();
}
return filterResults;
}
@Override
protected void publishResults(CharSequence contraint,
FilterResults results) {
if (results != null && results.count > 0) {
notifyDataSetChanged();
} else {
notifyDataSetInvalidated();
}
}
};
return myFilter;
}
}
Thank you in advance!
from
和to
在以下代码行中是什么意思:SimpleCursorAdapter a = new SimpleCursorAdapter(this, android.R.layout.simple_list_item_2, null, from, to, 0);
。 - Jaysuggestion
的任何东西。你是不是指的那个名为suggestions
的列表?@pskink - Jay