首页 > 系统 > Android > 正文

Android中AutoCompleteTextView自动提示

2019-12-12 04:20:41
字体:
来源:转载
供稿:网友

我们使用控件AutoCompleteTextView 自动提示时,有时需要设置BaseAdapter,设置BaseAdapter时,需要实现Filterable,手动进行筛选。

常用属性

布局只设置了至少输入一个字符显示提示

<AutoCompleteTextView    android:id="@+id/at"    android:completionThreshold="1"    android:layout_width="match_parent"    android:layout_height="wrap_content" />
 private List<String> allData = 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;    ArrayList<String> data;    @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<String> queryData = new ArrayList<>();        for (int i = 0; i < allData.size(); i++) {          if (allData.get(i).contains(prefix.toString())) {            queryData.add(allData.get(i));          }        }        results.values = queryData;        results.count = queryData.size();        return results;      }      /**       * 更新UI       */      @Override      protected void publishResults(CharSequence constraint, FilterResults results) {        List<String> queryData = (List<String>) 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();          }      }    }  }

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持武林网。

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表