How To Restrict Edittext To Some Particular Characters In Android?
searchEdit.setKeyListener(DigitsKeyListener.getInstance('abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789 &')); I used the above statement for restricting my edi
Solution 1:
First try with adding the android:digits="abcde.....012345789"
attribute.Although the android:digits
specify that it is a numeric field but it accept letters as well.
OR
try this code..
t1 = (EditText)findViewById(R.id.text);
t1.setFilters(new InputFilter[] {
new InputFilter() {
public CharSequence filter(CharSequence src, int start,
int end, Spanned dst, int dstart, int dend) {
if(src.equals("")){ // for backspacereturn src;
}
if(src.toString().matches("[a-zA-Z0-9 ]*")) //put your constraints here
{
return src;
}
return"";
}
}
});
OR
see an useful example from This Link
Solution 2:
Try to change the filter method of you Listener:
InputFilter[] filters = new InputFilter[1];
filters[0] = new InputFilter(){
@Override
public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
if (end > start) {
char[] acceptedChars = newchar[]{'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z',
'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z',
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '&', ' '};
for (int index = start; index < end; index++) {
if (!new String(acceptedChars).contains(String.valueOf(source.charAt(index)))) {
return"";
}
}
}
returnnull;
}
};
searchEdit.setFilters(filters);
Post a Comment for "How To Restrict Edittext To Some Particular Characters In Android?"