如何在EditText TextChangedListener中删除递归?

时间:2013-12-24 19:23:06

标签: android

我想从编辑文本中删除一些坏词。父亲叔叔Cousin King将是F ** K ...但问题是如果我改变文本它再来改变处理程序。任何人都知道解决方案请帮忙。代码在那里。

search_name.addTextChangedListener(new TextWatcher(){
        public void afterTextChanged(Editable s) {
            search_name.setText(s.toString().replace("something", "s**ething"));
            // here comes it repeatedly
        }
        public void beforeTextChanged(CharSequence s, int start, int count, int after){}
        public void onTextChanged(CharSequence s, int start, int before, int count){}
    });

4 个答案:

答案 0 :(得分:2)

我同意@ njzk2评论re:InputFilter,如果递归是你要解决的麻烦,你可以尝试这样的事情来阻止它:

// make your TextWatcher a class variable
protected TextWatcher mTextWatcher = new TextWatcher()
    {
        public void afterTextChanged(Editable s) {
            textFixerUpper(search_name, s.toString());
        }
        public void beforeTextChanged(CharSequence s, int start, int count, int after){}
        public void onTextChanged(CharSequence s, int start, int before, int count){}
    };


protected textFixerUpper(EditText t, String s)
{
 t.removeTextChangedListener(mTextWatcher);             // remove the listener
 t.setText(s.replace("something", "s**ething"));        // update the text
 t.addTextChangedListener(mTextWatcher);                // add the listener back
}

或者通过设置布尔标志而不是删除并重新添加监听器......虽然看起来有点混乱。

答案 1 :(得分:1)

您可以通过Editable方法提供的afterTextChanged(e: Editable)实例操作文字:

val textWatcher = object : TextWatcher {
    override fun afterTextChanged(e: Editable) {
        e.insert(0, "Hello World")
        // e.delete(st, en) ...
    }

    override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) { }

    override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) { }
}

在这种情况下不会调用侦听器方法。

答案 2 :(得分:0)

我用变量解决了它。从@ njzk2获得了想法

int checker = 0;
search_name.addTextChangedListener(new TextWatcher(){
        public void afterTextChanged(Editable s) {
            checker = 0;
        }
        public void beforeTextChanged(CharSequence s, int start, int count, int after){}
        public void onTextChanged(CharSequence s, int start, int before, int count){
            if(checker!=1)
            {    
               checker = 1;
               search_name.setText(s.toString().replace("something", "s**ething"));
            }
        }
    });

答案 3 :(得分:0)

最简单的方法是控制countbefore的值

view.addTextChangedListener(
    ...

    @Override
    public void onTextChanged(CharSequence charSequence, int start, int before, int count) {
        if ( count - before != 0) {
            onTextChange(charSequence);
        }
    }

);