如何在 Android 中使用模式创建搜索视图

How to make search view with modal in Android

我想制作一个像下图这样的 searchViewsearchView 从本地数据库接收数据,然后像 AutoCompleteTextView 一样过滤数据。 我怎样才能做到?

这是图片:

enter image description here

我使用 RecyclerView 作为列表显示项,在 Adapter 中我实现了一个 Filterable:

private List<Bank> banksList;
private List<Bank> bankListFiltered;
@Override
public Filter getFilter() {
    return new Filter() {
        @Override
        protected FilterResults performFiltering(CharSequence constraint) {
            String charString = constraint.toString();
            if (charString.isEmpty()) {
                bankListFiltered = banksList;
            } else {
                List<Bank> filteredList = new ArrayList<>();
                for (Bank row : banksList) {
                    String shortName = row.getShortName().toLowerCase();
                    if (shortName.contains(charString)) {
                        filteredList.add(row);
                    }
                }

                bankListFiltered = filteredList;
            }

            FilterResults filterResults = new FilterResults();
            filterResults.values = bankListFiltered;
            return filterResults;
        }

        @Override
        protected void publishResults(CharSequence constraint, FilterResults results) {
            bankListFiltered = (ArrayList<Bank>) results.values;
            notifyDataSetChanged();
        }
    };
}

@Override
public int getItemCount() {
    return bankListFiltered.size();
}

public BanksAdapter(List<Bank> banksList) {
    this.banksList = banksList;
    this.bankListFiltered = banksList;
}

在我的 activity 中,为 SearchView 添加事件:

new SearchView(this).setOnQueryTextListener(new SearchView.OnQueryTextListener() {
        @Override
        public boolean onQueryTextSubmit(String query) {

            return true;
        }

        @Override
        public boolean onQueryTextChange(String newText) {
            banksAdapter.getFilter().filter(newText);
            return true;
        }
    });