AutoCompleteTextView allow only suggested options
Asked Answered
T

1

9

I have a DialogFragment that contains AutoCompleteTextView, and Cancel and OK buttons.

The AutoCompleteTextView is giving suggestions of usernames that I'm getting from server.

What I want to do is to restrict the user to be able to enter only existing usernames.

I know I can do check if that username exists when the user clicks OK, but is there some other way, let's say not allow the user to enter character if there doesn't exist such username. I don't know how to do this because on each entered character I'm getting only up to 5 suggestions. The server is implemented that way.

Any suggestions are welcomed. Thank you

Tibetan answered 27/8, 2013 at 13:35 Comment(4)
Use Spinner instead ...Rhee
@Rhee I can't use spinner because there are a LOT of usernames, and the client wants to have autocomplete textview. Thank you for your suggestionTibetan
how about list view with search option?Gentle
@SunilMishra I can't use that either. The client wants only autocomplete, nothing else :)Tibetan
T
17

I couldn't find more suitable solution then this:

I added this focus change listener

actName.setOnFocusChangeListener(new OnFocusChangeListener() {
        public void onFocusChange(View v, boolean hasFocus) {
            if (!hasFocus) {
                ArrayList<String> results =
                        ((UsersAutoCompleteAdapter) actName.getAdapter()).getAllItems();
                if (results.size() == 0 ||
                        results.indexOf(actName.getText().toString()) == -1) {
                    actName.setError("Invalid username.");
                };
            }
        }
});

Where the method getAllItems() returns the ArrayList containing the suggestions.

So when I enter some username, and then move to another field this listener is triggered and it checks if the suggestions list is not empty and if the entered username is in that list. If the condition is not satisfied, an error is shown.

Also I have the same check on OK button click:

private boolean checkErrors() {

    ArrayList<String> usernameResults =
            ((UsersAutoCompleteAdapter) actName.getAdapter()).getAllItems();

    if (actName.getText().toString().isEmpty()) {
        actName.setError("Please enter a username.");
        return true;
    } else if (usernameResults.size() == 0 || usernameResults.indexOf(actName.getText().toString()) == -1) {
        actName.setError("Invalid username.");
        return true;
    }

    return false;
}

So if the AutoComplete view is still focused, the error check is done again.

Tibetan answered 29/8, 2013 at 10:16 Comment(3)
what is UsersAutoCompleteAdapter?Margarito
@Wizard It's my custom ListAdapter that I use for the AutocompleteTextView. That's just the name of the adapter.Tibetan
need help #46377623Laboratory

© 2022 - 2024 — McMap. All rights reserved.