AutoCompleteTextView allows only suggested options

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

AutoCompleteTextView gives suggestions about the user names that I get from the server.

What I want to do is restrict the user from entering only existing user names.

I know that I can check if this username exists when the user clicks OK , but is there another way, for example, to prevent the user from entering a character if that username does not exist. I do not know how to do this, because for each character I enter, I get only up to 5 sentences. The server is implemented in this way.

Any suggestions are welcome. Thanks you

+7
android android-dialogfragment dialogfragment autocompletetextview
source share
1 answer

I could not find a more suitable solution, and then the following:

I added a 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."); }; } } }); 

If the getAllItems() method returns an ArrayList containing the sentences.

So, when I enter some kind of username and then switch to another field, this listener starts up and it checks if the list of offers is empty and if the entered username is in this list. If the condition is not met, an error is displayed.

I also have the same check on the OK button:

 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.

+10
source share

All Articles