TextWatcher监听EditText的文本变化之后动态改变EditText里面的内容

使用TextWatcher对EditText进行监听,当EditText中值为某一特定内容时,将EditText中的值设为我们需要的那个值。一开始就是简单的在EditText中使用setText(…)来实现,结果出现栈溢出的异常。这里提供一个解决方案:当判断条件满足时,在afterTextChanged()方法中将TextWatcher移除掉,然后设置EditText的值,接着把TextWatcher重新设置进去

public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
editText = (EditText) findViewById(R.id.editText);
myTextWathcer = new MyTextWathcer();
editText.addTextChangedListener(myTextWathcer);
}

private class MyTextWathcer implements TextWatcher{

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count,
            int after) {

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before,
            int count) {

    }

    @Override
    public void afterTextChanged(Editable s) {
        int i = 0;
        try {
            i = Integer.valueOf(s.toString());
        } catch (Exception e) {
            e.printStackTrace();
        }
        if(i == 111){
            editText.removeTextChangedListener(this);
            setMyText();
        }
    }
}

private void setMyText(){
    editText.setText("11111new");
    editText.addTextChangedListener(myTextWathcer);
}

为什么在自己类的方法中将自己移除不会出错?
TextView类的removeTextChangedListener()方法中看一下就会明白了:
public void removeTextChangedListener(TextWatcher watcher) {
if (mListeners != null) {
int i = mListeners.indexOf(watcher);

        if (i >= 0) {
            mListeners.remove(i);
        }
    }
}

你可能感兴趣的:(修改)