Android : Allowing specific characters using input filter for edittext in android

on Saturday, September 27, 2014


I have an edittext for which i have set an input filter as follows:



filter_username = new InputFilter() {
public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
boolean keepOriginal = true;
StringBuilder sb = new StringBuilder(end - start);
for (int i = start; i < end; i++) {

char c = source.charAt(i);

if (isCharAllowed2(c)) // put your condition here
sb.append(c);
else
keepOriginal = false;
}
if (keepOriginal)
return null;
else {
if (source instanceof Spanned) {
SpannableString sp = new SpannableString(sb);
TextUtils.copySpansFrom((Spanned) source, start, sb.length(), null, sp, 0);
return sp;
} else {
return sb;
}
}
}

private boolean isCharAllowed2(char c) {
return Character.isLetterOrDigit(c);

}

};

txtusername.setFilters(new InputFilter[]{filter_username});


The issue is i want to do the following changes to the above filter:


1) The first character should not be a digit 2) Underscore and dot are the only characters allowed


Can you tell me how to modify the above filter in order to suit my requirements?


EDIT: I figured out the special characters part by the following changes:



private boolean isCharAllowed2(char c) {
return Character.isLetterOrDigit(c)||c=='_'||c=='.';

}


How do i prevent the first character from being a digit or a period?


0 comments:

Post a Comment