Android自动完成匹配选项 [英] Android autocomplete matching options

查看:42
本文介绍了Android自动完成匹配选项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在我的应用程序中使用了AutoCompleteTextView,它提供了国家/地区名称建议.我的自动完成功能将输入的文本与建议列表中的每个单词进行匹配.例如,如果输入两个字母"ar",则会得到沙特阿拉伯"作为建议之一.

I am using an AutoCompleteTextView in my app which gives countries names suggestions. My autocomplete is matching the entered text with every word in the suggestions list. For example, if I enter the two letters "ar", I get "Saudi Arabia" as one of the suggestions.

有什么方法可以使AutoCompleteTextView尝试仅从第一个单词开始进行匹配吗?也就是说,建议必须以输入的文本开头,在我之前的示例中,我会收到亚美尼亚",阿根廷"和仅限阿鲁巴".

Is there any way to make the AutoCompleteTextView tries to match only starting from the first word? i.e. the suggestion must start with entered text, in case of my previous example, I get suggestions like "Armenia", "Argentina" & "Aruba" only.

推荐答案

问题是 ArrayAdapter 中的 Filter 实现首先检查字符串是否以搜索约束开头,然后分割字符串并检查每个单词.

The problem is the Filter implementation within ArrayAdapter first checks if the string starts with the search constraint, and then splits the string and checks each individual word.

从ArrayAdapter.java:

From ArrayAdapter.java:

// First match against the whole, non-splitted value
if (valueText.startsWith(prefixString)) {
    newValues.add(value);
} else {
    final String[] words = valueText.split(" ");
    final int wordCount = words.length;

    // Start at index 0, in case valueText starts with space(s)
    for (int k = 0; k < wordCount; k++) {
        if (words[k].startsWith(prefixString)) {
            newValues.add(value);
            break;
        }
    }
}

如Daniel所述,您将需要实现自己的适配器,该适配器实现 Filterable .我创建了一个示例,可以实现您要查找的行为.您可以在此处找到.它重用了 ArrayAdapter 中的大多数代码.,但省略了分割字符串的部分.

As Daniel mentioned, you will need to implement your own adapter that implements Filterable. I've created an example that achieves the behavior you're looking for. You can find it here. It reuses most of the code within ArrayAdapter, but omits the part that splits the strings.

这篇关于Android自动完成匹配选项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆