AutoCompleteTextView allow only suggested options

前端 未结 1 1589
离开以前
离开以前 2021-01-04 23:55

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

The AutoCompleteText

1条回答
  •  盖世英雄少女心
    2021-01-05 00:23

    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 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 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.

    0 讨论(0)
提交回复
热议问题