Raiv
Raiv

Reputation: 5781

AutoCompleteTextView - how to disable dropdown when we have one exact match after filtering?

Is there an easy way to do so? Because dropdown with one element which is identical to typed text looks redundant.

My adapter is simple, here is the code

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

emailsSet.toEmailStringSet() returns set of Strings.

When I fill autoCompleteTextViewAddress with email identical to one in string set, I can still view a dropdown with one element.

Upvotes: 4

Views: 711

Answers (2)

Raiv
Raiv

Reputation: 5781

Ugly solution, but it works:

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;

    }


}

Use custom class instead of original AutoCompleteTextView.

Overrided enoughToFilter function hides dropdown when we have exactly one matching record in our adapter

Upvotes: 1

Mahyar Ebadi
Mahyar Ebadi

Reputation: 143

Depends on the type of code

But here is a SQL example of grabbing the suggestions

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

That way it would only show when it has 2 or more suggestions.

Upvotes: 0

Related Questions