AutoCompleteTextView仅允许建议的选项

nik*_*min 9 android autocompletetextview android-dialogfragment dialogfragment

我有一个DialogFragment包含AutoCompleteTextView,以及CancelOK按钮.

AutoCompleteTextView是给我是从服务器获取用户名的建议.

我想要做的是限制用户只能输入现有的用户名.

我知道我可以在用户点击时检查该用户名是否存在OK,但是还有其他方式,假设如果不存在此类用户名,则不允许用户输入字符.我不知道该怎么做,因为在每个输入的角色上我只得到5个建议.服务器以这种方式实现.

欢迎任何建议.谢谢

nik*_*min 14

我无法找到更合适的解决方案:

我添加了这个焦点改变监听器

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.");
                };
            }
        }
});
Run Code Online (Sandbox Code Playgroud)

方法getAllItems()返回ArrayList包含建议的位置.

因此,当我输入一些用户名,然后移动到另一个字段时,将触发此侦听器,并检查建议列表是否为空以及输入的用户名是否在该列表中.如果不满足条件,则显示错误.

OK点击按钮也一样检查:

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;
}
Run Code Online (Sandbox Code Playgroud)

因此,如果AutoComplete视图仍然聚焦,则再次执行错误检查.