AutoCompleteTextView 适配器返回旧值

Din*_*uka 5 android autocompletetextview

我实现了一个 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()));
Run Code Online (Sandbox Code Playgroud)

定制适配器:

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;
    }
}
Run Code Online (Sandbox Code Playgroud)

先感谢您!

小智 0

 actv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                suggestionAdapter.clear;
            }
        });
Run Code Online (Sandbox Code Playgroud)

当用户单击自动完成时,删除旧适配器。但为此您需要首先定义suggesstionAdapter。每次更新此适配器并将其设置为自动完成