自动完成 TextView Android。完成第一个字母

AutoComplete TextView Android. Complete with first letters

我在 autoCompleteTextView 中的适配器是这样的:

如果我输入“p”,它现在的工作方式将出现在下拉列表中 apple, pear and grape 因为它们进行匹配,但我只想让它显示 pear,因为它是唯一以 p 开头的词。所以,问题是:我怎样才能告诉 autoComplete 的 dropDownList 显示以我正在搜索的内容开头的单词的匹配项,而不显示包含它的其他位置不是第一个的单词。 例如,如果我键入“pe”,我只想显示 pear 而不是 grape,因为 pear 以该字符串开头。 这是我的代码

ArrayList<String> data = dbHelper.getDataAsString();
ArrayAdapter adapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, data);
autoCompleteTv.setAdapter(adapter);
autoCompleteTv.setThreshold(2);

以此为参考。刚刚制作完成后测试了这段代码,应该可以正常工作。

假设您的列表只有字符串类型。

private String[] searchableList = {"apple", "pear", "grape"};

我制作了这个函数,它采用 query 和 returns 新格式化的字符串列表。

    private List<String> filterQuery(String query) {
        // This takes all strings items which are valid with query
        List<String> filterList = new ArrayList<>();
        
        // Looping into each item from the list
        for (String currentString : searchableList) {
            // Make sure everything is lower case.
            String myString = currentString.toLowerCase(Locale.getDefault());
            // Take first two characters from the string, you may change it as required.
            String formatTitle = myString.substring(0, 2);
            // If query matches the current string add it to filterList
            if (formatTitle.contains(query)) {
                filterList.add(formatTitle);
            }
        }
        return filterList;
    }

让我知道进展如何。