How to restrict TextView to allow only alpha-numeric characters in Android
I have a TextView in my app that i want a user to be able to only enter alpha-numeric characters in. 开发者_如何学PythonHow can this be done? Thanks!
In the XML, put this:
android:digits="abcdefghijklmnopqrstuvwxyz1234567890 "
Here is a better solution......... https://groups.google.com/forum/?fromgroups=#!topic/android-developers/hS9Xj3zFwZA
InputFilter filter = new InputFilter() {
public CharSequence filter(CharSequence source, int start, int end,
Spanned dest, int dstart, int dend) {
for (int i = start; i < end; i++) {
if (!Character.isLetterOrDigit(source.charAt(i))) {
return "";
}
}
return null;
}
};
edit.setFilters(new InputFilter[]{filter});
The InputFilter
solution works well, and gives you full control to filter out input at a finer grain level than android:digits
. The filter()
method should return null
if all characters are valid, or a CharSequence
of only the valid characters if some characters are invalid. If multiple characters are copied and pasted in, and some are invalid, only the valid characters should be kept (@AchJ's solution will reject the entire paste if any characters a invalid).
public static class AlphaNumericInputFilter implements InputFilter {
public CharSequence filter(CharSequence source, int start, int end,
Spanned dest, int dstart, int dend) {
// Only keep characters that are alphanumeric
StringBuilder builder = new StringBuilder();
for (int i = start; i < end; i++) {
char c = source.charAt(i);
if (Character.isLetterOrDigit(c)) {
builder.append(c);
}
}
// If all characters are valid, return null, otherwise only return the filtered characters
boolean allCharactersValid = (builder.length() == end - start);
return allCharactersValid ? null : builder.toString();
}
}
Also, when setting your InputFilter
, you must make sure not to overwrite other InputFilters
set on your EditText
; these could be set in XML, like android:maxLength
. You must also consider the order that the InputFilters
are set. When used in conjunction with a length filter, your custom filter should be inserted before the length filter, that way pasted text applies the custom filter before the length filter (@AchJ's solution will overwrite all other InputFilters
and only apply the custom one).
// Apply the filters to control the input (alphanumeric)
ArrayList<InputFilter> curInputFilters = new ArrayList<InputFilter>(Arrays.asList(editText.getFilters()));
curInputFilters.add(0, new AlphaNumericInputFilter());
InputFilter[] newInputFilters = curInputFilters.toArray(new InputFilter[curInputFilters.size()]);
editText.setFilters(newInputFilters);
This should work:
textView.setInputType(InputType.TYPE_CLASS_NUMBER);
精彩评论