亚洲激情专区-91九色丨porny丨老师-久久久久久久女国产乱让韩-国产精品午夜小视频观看

溫馨提示×

如何讓Android選擇框支持模糊搜索

小樊
135
2024-07-25 00:19:13
欄目: 編程語言

要讓Android選擇框支持模糊搜索,可以通過自定義適配器來實現。下面是一個簡單的示例代碼:

  1. 首先,創建一個自定義的適配器類,繼承自BaseAdapter,并實現Filterable接口:
public class CustomAdapter extends BaseAdapter implements Filterable {
    private List<String> originalList;
    private List<String> filteredList;
    private Context context;

    public CustomAdapter(List<String> originalList, Context context) {
        this.originalList = originalList;
        this.filteredList = originalList;
        this.context = context;
    }

    @Override
    public int getCount() {
        return filteredList.size();
    }

    @Override
    public Object getItem(int position) {
        return filteredList.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        TextView textView = new TextView(context);
        textView.setText(filteredList.get(position));
        return textView;
    }

    @Override
    public Filter getFilter() {
        return new Filter() {
            @Override
            protected FilterResults performFiltering(CharSequence constraint) {
                FilterResults results = new FilterResults();
                List<String> filteredValues = new ArrayList<>();

                for (String value : originalList) {
                    if (value.toLowerCase().contains(constraint.toString().toLowerCase())) {
                        filteredValues.add(value);
                    }
                }

                results.values = filteredValues;
                results.count = filteredValues.size();
                return results;
            }

            @Override
            protected void publishResults(CharSequence constraint, FilterResults results) {
                filteredList = (List<String>) results.values;
                notifyDataSetChanged();
            }
        };
    }
}
  1. 在Activity或Fragment中使用自定義適配器類:
List<String> dataList = new ArrayList<>();
// 添加數據到dataList中

AutoCompleteTextView autoCompleteTextView = findViewById(R.id.autoCompleteTextView);
CustomAdapter adapter = new CustomAdapter(dataList, this);
autoCompleteTextView.setAdapter(adapter);

通過以上步驟,就可以讓Android選擇框支持模糊搜索了。用戶在輸入框中輸入關鍵詞時,選擇框會自動篩選出包含該關鍵詞的選項并顯示出來。

0
巍山| 旬邑县| 威信县| 喀什市| 晴隆县| 晋宁县| 望江县| 庆安县| 三河市| 镇远县| 大名县| 谷城县| 金昌市| 隆安县| 屏边| 海伦市| 博白县| 丰台区| 旺苍县| 磐石市| 淮安市| 台江县| 保靖县| 芦山县| 惠水县| 荣昌县| 上林县| 剑河县| 九龙坡区| 广饶县| 永泰县| 凉城县| 武安市| 昆明市| 安远县| 历史| 内江市| 赤峰市| 嘉禾县| 班戈县| 河东区|