我把TextInputEditText作为名字只接受字母但我有问题。
<android.support.design.widget.TextInputLayout
android:id="@+id/tvfnameinput"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<android.support.design.widget.TextInputEditText
android:id="@+id/etFirstname"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:digits="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
android:hint="firstname"
android:imeOptions="actionNext"
android:maxLength="12"
android:maxLines="1"
android:text="" />
</android.support.design.widget.TextInputLayout>
正如您在上面的布局中看到的那样,我设置了maxlength 12,所以如果我输入了12个数值,那么它不会被接受,但它会计数,所以我输入后无法输入字母12数值。
注意 - :我只想要字母表,而我的代码正常工作,但是当我输入数字值时,它不接受,但算作maxlenght。
编辑 - :android:imeOptions =&#34; actionNext&#34;我设置了android:digits =&#34; abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ&#34;
答案 0 :(得分:1)
如果您只想设置字母,那么您可以使用InputFilter而不是数字。从您的布局中删除此标记digit
。
以下是可以帮助您的示例:
edittext.setFilters(new InputFilter[] {
new InputFilter() {
public CharSequence filter(CharSequence src, int start,
int end, Spanned dst, int dstart, int dend) {
if(src.equals("")){ // for backspace
return src;
}
if(src.toString().matches("[a-zA-Z ]+")){
return src;
}
return "";
}
}
});
试试这个。它由我自己测试并且像魅力一样工作
editText.setFilters(new InputFilter[]{new InputFilter() {
@Override
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 (isCharAllowed(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 isCharAllowed(char c) {
Pattern ps = Pattern.compile("^[a-zA-Z ]+$");
Matcher ms = ps.matcher(String.valueOf(c));
return ms.matches();
}
}});
使用InputFilter时,会覆盖EditText的属性,然后可以使用InputFiler的最大长度。
试试这个
InputFilter[] inputFilters = new InputFilter[2];
inputFilters[0] = new InputFilter() {
@Override
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 (isCharAllowed(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 isCharAllowed(char c) {
Pattern ps = Pattern.compile("^[a-zA-Z ]+$");
Matcher ms = ps.matcher(String.valueOf(c));
return ms.matches();
}
};
inputFilters[1] = new InputFilter.LengthFilter(12);
editText.setFilters(inputFilters);