1. 程式人生 > >註冊暱稱時限制 中文7個字 字母21個

註冊暱稱時限制 中文7個字 字母21個

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" />