Android开发之EditText限制输入中文以及字数长度限制的标准姿势

老套路先上效果图:

Android开发之EditText限制输入中文以及字数长度限制的标准姿势_第1张图片

设置输入框的两个筛选器:

 etGiftName.setFilters(new InputFilter[]{new ZsInputFilter(5,this), new LengthListener(5,this)});

我们来看下筛选器如何实现的:

先看中文筛选器

package com.yhsh.mobile.giftcomponent;


import android.app.Activity;
import android.text.InputFilter;
import android.text.Spanned;
import android.widget.Toast;

/**
 * @author 下一页5(轻飞扬)
 *         创建时间:2019/8/4 16:38
 *         个人小站:http://yhsh.wap.ai(已挂)
 *         空间名称:group-wallet-android
 *         限制中文输入筛选器
 */
public class ZsInputFilter implements InputFilter {
    private Activity mActivity;
    private int maxValue;

    public ZsInputFilter(int maxValue, Activity shopPayActivity) {
        this.maxValue = maxValue;
        mActivity = shopPayActivity;
    }

    @Override
    public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
        for (int i = start; i < end; i++) {
            if (!isChinese(source.charAt(i))) {
                Toast.makeText(mActivity, "只能输入中文", Toast.LENGTH_SHORT).show();
                return "";
            } else {
                //是中文,提示最多5个汉字
                if (source.length() >= maxValue) {
                    Toast.makeText(mActivity, "最多只能输入" + maxValue + "个汉字", Toast.LENGTH_SHORT).show();
                }
            }
        }
        return null;
    }

    private static boolean isChinese(char c) {
        String regex = "[\\u4e00-\\u9fa5]";
        return String.valueOf(c).matches(regex);
    }
}

再看下长度筛选器:

package com.yhsh.mobile.giftcomponent;

import android.app.Activity;
import android.text.InputFilter;
import android.text.Spanned;
import android.widget.Toast;


/**
 * @author 下一页5(轻飞扬)
 *         创建时间:2019/8/5 10:21
 *         个人小站:http://yhsh.wap.ai(已挂)
 *         空间名称:group-wallet-android
 */
public class LengthListener implements InputFilter {
    private final int mMax;
    private Activity mActivity;

    public LengthListener(int max, Activity activity) {
        mMax = max;
        mActivity = activity;
    }

    @Override
    public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
        int keep = mMax - (dest.length() - (dend - dstart));
        if (keep <= 0) {
            Toast.makeText(mActivity, "最多只能输入" + mMax + "个汉字", Toast.LENGTH_SHORT).show();
            return "";
        } else if (keep >= end - start) {
            return null;
        } else {
            keep += start;
            if (Character.isHighSurrogate(source.charAt(keep - 1))) {
                --keep;
                if (keep == start) {
                    return "";
                }
            }
            return source.subSequence(start, keep);
        }
    }

    /**
     * @return the maximum length enforced by this input filter
     */
    public int getMax() {
        return mMax;
    }
}

 

你可能感兴趣的:(Android总结,限制中文,中文输入,android中文,EditText中文)