亲宝软件园·资讯

展开

AutoCompleteTextView自动提示 Android中AutoCompleteTextView自动提示

人气:0
想了解Android中AutoCompleteTextView自动提示的相关内容吗,在本文为您仔细讲解AutoCompleteTextView自动提示的相关知识和一些Code实例,欢迎阅读和指正,我们先划重点: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();
          }
      }

    }
  }

加载全部内容

相关教程
猜你喜欢
用户评论