AutoCompleteTextView allow only suggested options

南楼画角 提交于 2019-11-30 19:04:52

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.

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