我们使用控件AutoCompleteTextView 自动提示时,有时需要设置BaseAdapter,设置BaseAdapter时,需要实现Filterable,手动进行筛选。
常用属性
布局只设置了至少输入一个字符显示提示
private ListallData = new ArrayList<>(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); allData.add("aa"); allData.add("bb"); allData.add("cc"); allData.add("dd"); allData.add("abc"); allData.add("bcd"); AutoCompleteTextView textView = (AutoCompleteTextView) findViewById(R.id.at); MyAdapter adapter = new MyAdapter(); textView.setAdapter(adapter); }
adapter适配器代码
class MyAdapter extends BaseAdapter implements Filterable { DataFilter filter; ArrayListdata; @Override public int getCount() { if (data != null && data.size() > 0) { return data.size(); } return 0; } @Override public Object getItem(int i) { return null; } @Override public long getItemId(int i) { return 0; } @Override public View getView(int position, View view, ViewGroup viewGroup) { TextView textView = new TextView(MainActivity.this); textView.setText(data.get(position)); return textView; } @Override public Filter getFilter() { if (filter == null) { filter = new DataFilter(); } return filter; } private class DataFilter extends Filter { @Override protected FilterResults performFiltering(CharSequence prefix) { //查询结果保存到FilterResults对象里 FilterResults results = new FilterResults(); List queryData = new ArrayList<>(); for (int i = 0; i queryData = (List ) results.values; if (data == null) { data = new ArrayList<>(); } if (data.size() > 0) { data.clear(); } if (queryData != null && queryData.size() > 0) for (String string : queryData) { data.add(string); notifyDataSetChanged(); } } } }
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。