InputFilter letterFilter = new InputFilter() {
public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
String filtered = "";
for (int i = start; i < end; i++) {
char character = source.charAt(i);
if (!Character.isWhitespace(character)&&Character.isLetter(character)) {
filtered += character;
}
}
return filtered;
}
};
editText.setFilters(new InputFilter[]{letterFilter});
EditText yourEditText = (EditText) findViewById(R.id.yourEditText);
yourEditText.setFilters(new InputFilter[] {
new InputFilter() {
@Override
public CharSequence filter(CharSequence cs, int start,
int end, Spanned spanned, int dStart, int dEnd) {
// TODO Auto-generated method stub
if(cs.equals("")){ // for backspace
return cs;
}
if(cs.toString().matches("[a-zA-Z ]+")){
return cs;
}
return "";
}
}});
对科特林来说:
val yourEditText = findViewById<View>(android.R.id.yourEditText) as EditText
val reges = Regex("^[0-9a-zA-Z ]+$")
//this will allow user to only write letter and white space
yourEditText.filters = arrayOf<InputFilter>(
object : InputFilter {
override fun filter(
cs: CharSequence, start: Int,
end: Int, spanned: Spanned?, dStart: Int, dEnd: Int,
): CharSequence? {
if (cs == "") { // for backspace
return cs
}
return if (cs.toString().matches(reges)) {
cs
} else ""
}
}
)