AutoCompleteTextView allow only suggested options

孤街醉人 提交于 2019-12-30 06:12:09

问题


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


回答1:


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.



来源:https://stackoverflow.com/questions/18467012/autocompletetextview-allow-only-suggested-options

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!