android - EditText 限制输入特殊字符 : single quote, 双引号和表情符号

标签 android regex android-edittext

我在将特殊字符:单引号、双引号和表情符号从 editText 插入数据库时​​遇到问题。

我希望我的 editText 限制这些字符,我成功地限制了表情符号,但我未能限制用户输入单引号和双引号。

例如当我尝试将 editText 中的文本 Today's List 输入数据库时​​,它会生成异常。

我在 editText 中使用了 InputFilter 来过滤表情符号,我希望这个过滤器也能限制单引号和双引号。

public static InputFilter getEditTextFilterEmoji() {
    return new InputFilter() {

        @Override
        public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {

            CharSequence sourceOriginal = source;
            source = replaceEmoji(source);
            end = source.toString().length();

            if (end == 0)
                return ""; //Return empty string if the input character is already removed

            if (!sourceOriginal.toString().equals(source.toString())) {
                char[] v = new char[end - start];
                TextUtils.getChars(source, start, end, v, 0);

                String s = new String(v);

                if (source instanceof Spanned) {
                    SpannableString sp = new SpannableString(s);
                    TextUtils.copySpansFrom((Spanned) source, start, end, null, sp, 0);
                    return sp;
                } else {
                    return s;
                }
            } else {
                return null; // keep original
            }
        }

        private String replaceEmoji(CharSequence source) {

            String notAllowedCharactersRegex = "[^a-zA-Z0-9@#\\$%\\&\\-\\+\\(\\)\\*;:!\\?\\~`£\\{\\}\\[\\]=\\.,_/\\\\\\s'\\\"<>\\^\\|÷×]";
            return source.toString()
                    .replaceAll(notAllowedCharactersRegex, "");
        }
    };
}

谁能帮我解决这个问题?

最佳答案

限制 EditText 只使用给定的数字。

            <EditText
            ........
            android:inputType="textPersonName"
            android:digits="aAbBcCdDeEfFgGhHiIjJkKlLmMnNoOpPqQrRsStTuUvVwWxXyY zZ0123456789"
            />

关于android - EditText 限制输入特殊字符 : single quote, 双引号和表情符号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41499432/

相关文章:

java - 无法按照我想要的方式拆分字符串

regex - R - 字符串中的多个条件匹配

android - 获取 EditTextPreference 值

java - EditText 并使用按钮提交它们

android - Facebook - SingleInstance Activity 上的 LoginFragment

android - 如何使 TabHost 保持纵向并监听 configChanges(方向)

sql - REGEXP_REPLACE - 仅当包含在 () 中时才从字符串中删除新行\n

android - 如何以编程方式设置和删除 Focus on edit text on click a button

Android:GridLayout 的分隔线

java - 正则表达式查找字符返回 5 次