TextWatcher导致stackOverflow

时间:2014-05-21 22:19:44

标签: android listener stack-overflow

基本上,我有一个Editable(在这种情况下,它是TextView),其中有一个TextChangedListener(一个TextWatcher)我的问题是如何我可以stackOverflow的{​​{1}}回调中编辑afterTextChanged吗?

部分代码

TextWatcher

1 个答案:

答案 0 :(得分:2)

由于您在文本更改的侦听器中再次设置文本,因此导致无限循环。最简单的解决方法是使用布尔标志来过滤掉不是由用户引起的事件。尝试这样的事情:

private boolean userChange = true;

private void writeNewMsg() {
    final EditText newMsgText = (EditText)findViewById(R.id.s4_et_message);
    newMsgText.addTextChangedListener(new TextWatcher() {

        @Override
        public void afterTextChanged(Editable editable) {
            if (userChange) {
                // Event is invoked by the user, set flag to false to ignore the event caused by the following setText()
                userChange = false;

                // Save current selection so you can reapply it after setText()
                int selection = newMsgText.getSelectionStart();

                newMsgText.setText(Smiley.getSmiledText(Messaging.this, newMsgText.getText().toString()));

                // Reapply the previous selection
                newMsgText.setSelection(selection);
            } else {
                // Ignore this event, reset flag so next user interaction will not be ignored.
                userChange = true;
            }
        }

        @Override
        public void beforeTextChanged(CharSequence charSequence, int arg1, int arg2, int arg3) {

        }

        @Override
        public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {

        }
    });
}

当然这只是一个快速的解决方法。您可能需要在应用中使用更精细的解决方案。不过,这个例子应该足以说明你的基础知识。