android 给editview设置输入限制(比如不能输入表情),还有长度限制

mTitleEt.setFilters(new InputFilter[]{FilterUtil.getInputFilter(context,
        getString(R.string.filter_default), FilterUtil.MATCHER_DEFAULT),new InputFilter.LengthFilter(50)});
其中FilterUtil.getInputFilter是工具类
public class FilterUtil {
    //过滤表情正则表达式
    public static final String EMOJI = "[\ud83c\udc00-\ud83c\udfff]|[\ud83d\udc00-\ud83d\udfff]|[\u2600-\u27ff]";
    //匹配昵称
    public static final String MATCHER_NICKNAME = "[A-Za-z0-9_\\-\\u4e00-\\u9fa5]+";

    //匹配数字、中英文、标点符号
    public static final String MATCHER_DEFAULT = "[A-Za-z0-9_\\-\\u4e00-\\u9fa5\\p{P}]+";

    //过滤金额
    public static final String MATCHER_MONEY = "(^[1-9]\\d*(\\.\\d{1,2})?$)|(^[0]{1}(\\.\\d{1,2})?$)";

    //匹配中文字符
    public static final String MATCHER_CN = "[\\u4e00-\\u9fa5]";

    /**
     *
     * @param context
     * @return 返回EditText输入文本过滤器
     */
    public static InputFilter getInputFilter(final Context context,final String toast,final String regex){
        InputFilter inputFilter = new InputFilter() {
            @Override
            public CharSequence filter(CharSequence charSequence, int start, int end, Spanned dest, int dstart, int dend) {
                if(charSequence.length()>0){
                    if(isMatcher(charSequence.toString(),regex)){
                        return null;
                    }else{
                        Toast.makeText(context,toast,0).show();
                        return "";
                    }
                }
                return null;
            }
        };
        return inputFilter;
    }

    /**
     * 正则表达式匹配
     * @param content 待匹配内容
     * @param regex   正则表达式
     * @return true 匹配成功
     */
    public static boolean isMatcher(String content,String regex){
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(content);
        return matcher.find();
    }
}

你可能感兴趣的:(android 给editview设置输入限制(比如不能输入表情),还有长度限制)