实现只允许只入数字和字符
方法一:在XML文件中实现布局如下:
<EditText
android:layout_width="match_parent"
android:layout_height="10dp"
android:textSize="16sp"
android:digits="0123456789qwertzuiopasdfghjklyxcvbnm"
android:hint="Only letters, digits, _ and - allowed"
/>
方法二:在代码中实现:
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;
}
};
editText.setFilters(new InputFilter[]{filter});
如果需要控制长度:
最大不允许超过 12个字符
editText.setFilters(new InputFilter[]{new InputFilter.LengthFilter(12)});