我有一个edittext,我为其设置了一个输入过滤器,如下所示:
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});
问题是我想对上面的过滤器进行以下更改:
1)第一个字符应不为数字 2)下划线和点是唯一允许的字符
您能否告诉我如何修改上述过滤器以满足我的要求?
编辑: 我通过以下更改找出了特殊字符部分:
private boolean isCharAllowed2(char c) {
return Character.isLetterOrDigit(c)||c=='_'||c=='.';
}
如何防止第一个字符成为数字或句号?
答案 0 :(得分:0)
Character.isLetterOrDigit检查指定的字符是否为字母或数字。如果字符是字母,则使用Character.isLetter返回true
false
private boolean isCharAllowed2(char c) {
if(sb.length()==0)
return Character.isLetter(c);
else
return Character.isLetterOrDigit(c);
}
答案 1 :(得分:0)
这是您应该使用的功能,根据您已经找到的内容构建您所请求的功能:
1如何防止第一个字符成为数字或句点?
2下划线和点是唯一允许的字符(我假设您之前的编辑是指字母+数字+下划线+句号)
private boolean isCharAllowed2(char c, final int position) {
if(position == 0) // 0 position in your string
return ! (Character.isDigit(c) || c=='.'); // point 1
else
return Character.isLetterOrDigit(c)|| c=='_'|| c=='.'; // point 2
}
您可以在for循环中的代码中调用它:
for (int i = start; i < end; i++) {
char c = source.charAt(i);
if (isCharAllowed2(c, i)) // this passes the position of the character to your isCharAllowed2 function, allowing you to decide on the filtering there according to the position in the String
sb.append(c);
else
keepOriginal = false;
}