AutoCompleteTextView - 如何在过滤后只有一个精确匹配项时禁用下拉菜单?

4

有没有简单的方法可以做到这一点呢?因为只有一个与键入文本相同的元素的下拉菜单看起来很冗余。

我的适配器很简单,以下是代码

AutoCompleteTextView autoCompleteTextViewAddress;
...
    ArrayAdapter<String> adapter = new ArrayAdapter<String>(AvatarMainActivity.this, android.R.layout.simple_list_item_1, emailsSet.toEmailStringSet());
    autoCompleteTextViewAddress.setAdapter(adapter);

emailsSet.toEmailStringSet() 返回字符串集合。

当我使用与字符串集合中相同的电子邮件填充 autoCompleteTextViewAddress 时,仍然可以查看包含一个元素的下拉列表。

2个回答

1

不太美观的解决方案,但它能够正常工作:

public class CustomAutoCompleteTextView extends AutoCompleteTextView {

    public CustomAutoCompleteTextView(Context context) {
        super(context);
        // TODO Auto-generated constructor stub
    }
    public CustomAutoCompleteTextView(Context context, AttributeSet attrs)
    {
        super(context,attrs);
    }
    public CustomAutoCompleteTextView(Context context, AttributeSet attrs, int defStyle)
    {
        super(context,attrs,defStyle);
    }
    @Override
    public boolean enoughToFilter()
    {
        boolean isEnough=(getThreshold()<=this.getText().length());

        if(isEnough)
        {
            if(this.getAdapter()!=null)
            {
                int itemsCount=0;
                int matchIndex=0;
                String txt = this.getText().toString();
                for (int i=0; i< this.getAdapter().getCount();i++) 
                {
                    String dat = (String)this.getAdapter().getItem(i);
                    if(dat.startsWith(txt))
                    {
                        itemsCount++;
                        matchIndex=i;
                    }
                }
                if(itemsCount == 1)
                {
                     if(((String)getAdapter().getItem(matchIndex)).equals(txt))
                     {
                         isEnough=false;
                     }

                }
            }
        }
        return isEnough;

    }


}

使用自定义类替代原始的AutoCompleteTextView

重写enoughToFilter函数,当我们的适配器中恰好有一个匹配记录时,隐藏下拉菜单。


0

这取决于代码的类型。

但是这里有一个SQL示例,可以获取建议。

     If( (select count(*) from /* your code here */) > 1)
     Select /* field */ from /* your code again here */

这样只有当它有两个或更多建议时才会显示。


也许吧。看到你当前代码的简化版本会很有帮助。 - Mahyar Ebadi
添加了。那里没有 SQL,它更简单。 - Raiv

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接