name = findViewById(R.id.name); name.setFilters(new InputFilter[]{filter}); //限制字符输入21
String namestring=name.gettext().tostring();
/** * 限制用户输入名的字符长度21 */ InputFilter filter = new InputFilter() { final int maxLen = 21; @Override public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) { // TODO Auto-generated method stub int dindex = 0; int count = 0; while (count <= maxLen && dindex < dest.length()) { char c = dest.charAt(dindex++); if (c < 128) { count = count + 1; } else { count = count + 3; } } if (count > maxLen) { return dest.subSequence(0, dindex - 1); } int sindex = 0; while (count <= maxLen && sindex < source.length()) { char c = source.charAt(sindex++); if (c < 128) { count = count + 1; } else { count = count + 3; } } if (count > maxLen) { sindex--; } return source.subSequence(0, sindex); } };
<EditText android:layout_width="100dp" android:layout_height="wrap_content" android:layout_marginLeft="40dp" android:background="@mipmap/yuanjiao" android:hint="就你厉害" android:singleLine="true" android:maxLength="21" android:textColor="#ffffff" android:id="@+id/name" android:textColorHint="#4A6837" android:textSize="15sp" />