EditText length Chinese Filter - Android User Interface

Android examples for User Interface:EditText

Description

EditText length Chinese Filter

Demo Code


import android.annotation.TargetApi;
import android.os.Build;
import android.support.annotation.NonNull;
import android.text.Editable;
import android.text.InputFilter;
import android.text.InputType;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.ActionMode;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;

public class Main{
    //from ww  w .  j av a 2  s.  c o  m
    public static void lengthChineseFilter(final EditText editText,
            final int length) {
        InputFilter[] filters = new InputFilter[1];

        filters[0] = new InputFilter.LengthFilter(length) {
            public CharSequence filter(@NonNull CharSequence source,
                    int start, int end, @NonNull Spanned dest, int dstart,
                    int dend) {

                boolean isChinese = StringUtil.checkNameChese(source
                        .toString());
                if (!isChinese || dest.toString().length() >= length) {
                    return "";
                }
                return source;
            }
        };
        // Sets the list of input filters that will be used if the buffer is Editable. Has no effect otherwise.
        editText.setFilters(filters);
    }
}

Related Tutorials