的EditText和输入过滤原因重复文本(EditText and InputFilter caus

2019-07-29 14:55发布

我试图实现限制输入到阿尔法字符只有[A-ZA-Z]一个EditText。

我开始从输入过滤方法这篇文章 。 当我键入“A%”的文本,然后消失,如果我打退格文是“A”。 我试过在过滤器功能的其他变化就像使用正则表达式只匹配[A-ZA-Z],有时看到这样重复字符的疯狂行为,我将输入“A”,然后“B”,并获得“AAB”,然后“C”型,并获得“aabaabc”然后按退格并获得“aabaabcaabaabc”!

下面是我与迄今与我尝试了不同的方法使用的代码。

    EditText input = (EditText)findViewById( R.id.inputText );
    InputFilter filter = new InputFilter() {
        @Override
        public CharSequence filter( CharSequence source, int start, int end, Spanned dest, int dstart, int dend ) {
            //String data = source.toString();
            //String ret = null;
            /*
            boolean isValid = data.matches( "[A-Za-z]" );
            if( isValid ) {
                ret = null;
            }
            else {
                ret = data.replaceAll( "[@#$%^&*]", "" );
            }
            */
            /*
            dest = new SpannableStringBuilder();
            ret = data.replaceAll( "[@#$%^&*]", "" );
            return ret;
            */

            for( int i = start; i < end; i++ ) {
                if( !Character.isLetter( source.charAt( i ) ) ) {
                    return "";
                }
            }

            return null;
        }
    };
    input.setFilters( new InputFilter[]{ filter } );

我完全难倒这一个所以这里的任何帮助,将不胜感激。

编辑:好的,我已经做了很多与输入过滤实验,并得出了一些结论,虽然没有解决的问题。 请参阅我下面的代码中的注释。 我现在要去尝试伊姆兰林蛙的解决方案。

    EditText input = (EditText)findViewById( R.id.inputText );
    InputFilter filter = new InputFilter() {
        // It is not clear what this function should return!
        // Docs say return null to allow the new char(s) and return "" to disallow
        // but the behavior when returning "" is inconsistent.
        // 
        // The source parameter is a SpannableStringBuilder if 1 char is entered but it 
        // equals the whole string from the EditText.
        // If more than one char is entered (as is the case with some keyboards that auto insert 
        // a space after certain chars) then the source param is a CharSequence and equals only 
        // the new chars.
        @Override
        public CharSequence filter( CharSequence source, int start, int end, Spanned dest, int dstart, int dend ) {
            String data = source.toString().substring( start, end );
            String retData = null;

            boolean isValid = data.matches( "[A-Za-z]+" );
            if( !isValid ) {
                if( source instanceof SpannableStringBuilder ) {
                    // This works until the next char is evaluated then you get repeats 
                    // (Enter "a" then "^" gives "a". Then enter "b" gives "aab")
                    retData = data.replaceAll( "[@#$%^&*']", "" );
                    // If I instead always returns an empty string here then the EditText is blanked.
                    // (Enter "a" then "^" gives "")
                    //retData = "";
                }
                else { // source is instanceof CharSequence
                    // We only get here if more than 1 char was entered (like "& ").
                    // And again, this works until the next char is evaluated then you get repeats 
                    // (Enter "a" then "& " gives "a". Then enter "b" gives "aab")
                    retData = "";
                }
            }

            return retData;
        }
    };
    input.setFilters( new InputFilter[]{ filter } );

Answer 1:

使用下面的代码:

EditText input = (EditText) findViewById(R.id.inputText);
   input.addTextChangedListener(new TextWatcher() {

    public void onTextChanged(CharSequence s, int start, int before, int count) {
        // TODO Auto-generated method stub
         for( int i = start;i<s.toString().length(); i++ ) {
             if( !Character.isLetter(s.charAt( i ) ) ) {
                input.setText("");
             }
         }

    }

    public void beforeTextChanged(CharSequence s, int start, int count,
            int after) {
        // TODO Auto-generated method stub

    }

    public void afterTextChanged(Editable s) {
        // TODO Auto-generated method stub

    }
   });

如果你想有效的文字留在EditText上:


 input.addTextChangedListener(new TextWatcher() {

    public void onTextChanged(CharSequence s, int start, int before, int count) {
        // TODO Auto-generated method stub

    }

    public void beforeTextChanged(CharSequence s, int start, int count,
            int after) {
        // TODO Auto-generated method stub

    }
    public void afterTextChanged(Editable s) {
        // TODO Auto-generated method stub
         for( int i = 0;i<s.toString().length(); i++ ) {
             if( !Character.isLetter(s.charAt( i ) ) ) {                    
                s.replace(i, i+1,"");               
             }
         }
    }
   });


Answer 2:

我们也有类似的问题,我相信一个解决方案[0]会为你正常工作。 我们的要求是实现一个剥离富文本输入一个EditText。 例如,如果用户复制粗体来他们的剪贴板并粘贴入的EditText,在EditText上应该删除大胆强调造型和仅保留纯文本。

该解决方案类看起来是这样的:

public class PlainEditText extends EditText {
    public PlainEditText(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        addFilter(this, new PlainTextInputFilter());
    }

    private void addFilter(TextView textView, InputFilter filter) {
        InputFilter[] filters = textView.getFilters();
        InputFilter[] newFilters = Arrays.copyOf(filters, filters.length + 1);
        newFilters[filters.length] = filter;
        textView.setFilters(newFilters);
    }

    private static class PlainTextInputFilter implements InputFilter {
        @Override
        public CharSequence filter(CharSequence source, int start, int end, Spanned dest,
                                   int dstart, int dend) {
            return stripRichText(source, start, end);
        }

        private CharSequence stripRichText(CharSequence str, int start, int end) {
            // ...
        }
    }
}

我们最初的实施stripRichText()很简单:

// -- BROKEN. DO NOT USE --
String plainText = str.subSequence(start, end).toString();
return plainText;

Java的基础String类不保留任何样式的信息,以便为CharSequence接口转换为具体的字符串拷贝只纯文本。

我们没有意识到的是,部分Android软键盘添加和依靠错别字​​和其他东西临时组成的提示。 该问题通过去除提示以及以意想不到的方式(通常加倍整个的EditText字段的输入)重复字符表现。 对于InputFilter.filter文档[1]()进行通信的要求是这样的:

 * Note: If <var>source</var> is an instance of {@link Spanned} or
 * {@link Spannable}, the span objects in the <var>source</var> should be 
 * copied into the filtered result (i.e. the non-null return value). 

我相信,妥善解决是保存临时跨度:

   /** Strips all rich text except spans used to provide compositional hints. */
    private CharSequence stripRichText(CharSequence str, int start, int end) {
        String plainText = str.subSequence(start, end).toString();
        SpannableString ret = new SpannableString(plainText);
        if (str instanceof Spanned) {
            List<Object> keyboardHintSpans = getComposingSpans((Spanned) str, start, end);
            copySpans((Spanned) str, ret, keyboardHintSpans);
        }
        return ret;
    }

    /**
     * @return Temporary spans, often applied by the keyboard to provide hints such as typos.
     *
     * @see {@link android.view.inputmethod.BaseInputConnection#removeComposingSpans}
     * @see {@link android.inputmethod.latin.inputlogic.InputLogic#setComposingTextInternalWithBackgroundColor}
     */
    @NonNull private List<Object> getComposingSpans(@NonNull Spanned spanned,
                                                    int start,
                                                    int end) {
        // TODO: replace with Apache CollectionUtils.filter().
        List<Object> ret = new ArrayList<>();
        for (Object span : getSpans(spanned, start, end)) {
            if (isComposingSpan(spanned, span)) {
                ret.add(span);
            }
        }
        return ret;
    }

    private Object[] getSpans(@NonNull Spanned spanned, int start, int end) {
        Class<Object> anyType = Object.class;
        return spanned.getSpans(start, end, anyType);
    }

    private boolean isComposingSpan(@NonNull Spanned spanned, Object span) {
        return isFlaggedSpan(spanned, span, Spanned.SPAN_COMPOSING);
    }

    private boolean isFlaggedSpan(@NonNull Spanned spanned, Object span, int flags) {
        return (spanned.getSpanFlags(span) & flags) == flags;
    }

[0]可以在这里找到实际实现: https://git.wikimedia.org/blob/apps%2Fandroid%2Fwikipedia/e9ddd8854ff15cde791a2e6fb7754a5450d6f7cf/app%2Fsrc%2Fmain%2Fjava%2Forg%2Fwikipedia%2Frichtext%2FRichTextUtil.java

[1] https://android.googlesource.com/platform/frameworks/base/+/029942f77d05ed3d20256403652b220c83dad6e1/core/java/android/text/InputFilter.java#37



Answer 3:

宾果,我发现这个问题!

当我使用Android:在EditText上cursorVisible =“假”的开始和DSTART参数不正确匹配。

启动参数仍然是我始终为0,但DSTART参数也总是0,因此只要我使用.replaceAll无效()。 这是相反的是这个帖子是这样说的我不太明白为什么,但至少我可以建立一些作品吧!



Answer 4:

我只是想给我的解决方案添加到问题(如迟到,因为它是)。 我发现,如果添加

    yourEditText.setInputType(InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS);

然后退格问题停止



Answer 5:

修正了重复的文字,工作在所有的Android版本:

public static InputFilter getOnlyCharactersFilter() {
    return getCustomInputFilter(true, false, false);
}

public static InputFilter getCharactersAndDigitsFilter() {
    return getCustomInputFilter(true, true, false);
}

public static InputFilter getCustomInputFilter(final boolean allowCharacters, final boolean allowDigits, final boolean allowSpaceChar) {
    return new InputFilter() {
        @Override
        public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
            boolean keepOriginal = true;
            StringBuilder sb = new StringBuilder(end - start);
            for (int i = start; i < end; i++) {
                char c = source.charAt(i);
                if (isCharAllowed(c)) {
                    sb.append(c);
                } else {
                    keepOriginal = false;
                }
            }
            if (keepOriginal) {
                return null;
            } else {
                if (source instanceof Spanned) {
                    SpannableString sp = new SpannableString(sb);
                    TextUtils.copySpansFrom((Spanned) source, start, sb.length(), null, sp, 0);
                    return sp;
                } else {
                    return sb;
                }
            }
        }

        private boolean isCharAllowed(char c) {
            if (Character.isLetter(c) && allowCharacters) {
                return true;
            }
            if (Character.isDigit(c) && allowDigits) {
                return true;
            }
            if (Character.isSpaceChar(c) && allowSpaceChar) {
                return true;
            }
            return false;
        }
    };
}

现在你可以使用这个文件管理器,如:

 //Accept Characters Only
edit_text.setFilters(new InputFilter[]{getOnlyCharactersFilter()});

//Accept Digits and Characters
edit_text.setFilters(new InputFilter[]{getCharactersAndDigitsFilter()});

//Accept Digits and Characters and SpaceBar
edit_text.setFilters(new InputFilter[]{getCustomInputFilter(true,true,true)});


文章来源: EditText and InputFilter cause repeating text