Android中AutoCompleteTextView自动提示

2019/7/7 21:04:32

本文主要是介绍Android中AutoCompleteTextView自动提示,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

我们使用控件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();
          }
      }

    }
  }

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



这篇关于Android中AutoCompleteTextView自动提示的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程