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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With