Reputation: 2007
I want user to enter just one character. I thought to make buttons for every letter, but this is useless. Could you recommend something to overcome this problem? Thanks in advance..
Upvotes: 0
Views: 932
Reputation: 1830
You can use an InputFilter.LengthFilter to limit the number of characters that can be entered into a text field and a custom InputFilter to restrict the characters that are allowed; which sounds like the simplest approach to me.
Here's an example:
EditText myTextField = (EditText) findViewById(R.id.my_text);
InputFilter validCharsInputFilter = new InputFilter() {
@Override
public CharSequence filter(CharSequence source, int start, int end,
Spanned dest, int dstart, int dend) {
// Loop through characters being inserted
for (int i = start; i < end; i++) {
// If it is not a letter
if (!Character
.isLetter(source.charAt(i))) {
// Return empty string - as char not allowed
return "";
}
}
// If we've got this far, then return null to accept string
return null;
}
};
myTextField.setFilters(
new InputFilter[] { new InputFilter.LengthFilter(1), validCharsInputFilter });
Upvotes: 2
Reputation: 5389
You could among other solutions make a field and set your event handler to only accept one character at the time.
This is very close to that question: Validation on Edit Text
Upvotes: 0