欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  移动技术

Android中AutoCompleteTextView自动提示

程序员文章站 2024-02-27 22:34:09
我们使用控件autocompletetextview 自动提示时,有时需要设置baseadapter,设置baseadapter时,需要实现filterable,手动进行筛...

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

Android中AutoCompleteTextView自动提示

常用属性

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

<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();
          }
      }

    }
  }

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