首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >TextWatcher导致stackOverflow

TextWatcher导致stackOverflow
EN

Stack Overflow用户
提问于 2014-05-21 22:19:44
回答 1查看 220关注 0票数 1

基本上,我有一个Editable (在本例中是一个TextView),它有一个TextChangedListener (一个TextWatcher),我的问题是当在TextWatcherafterTextChanged回调中编辑它时,如何才能而不是导致stackOverflow

一些代码

代码语言:javascript
复制
private void writeNewMsg() {
    final EditText newMsgText = (EditText)findViewById(R.id.s4_et_message);
    newMsgText.addTextChangedListener(new TextWatcher() {

        @Override
        public void afterTextChanged(Editable editable) {
            newMsgText.setText(Smiley.getSmiledText(Messaging.this, newMsgText.getText().toString()));
            // The above line of code causes the stackOverflow
        }

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

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

回答 1

Stack Overflow用户

回答已采纳

发布于 2014-05-21 22:25:17

由于要在文本更改侦听器中再次设置文本,所以会导致无限循环。最简单的修复方法是使用布尔标志过滤出不是由用户引起的事件。试着做这样的事情:

代码语言:javascript
复制
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) {

        }
    });
}

当然,这只是一个快速的解决办法。您可能需要一个更精细的解决方案在您的应用程序。尽管如此,这个示例应该足以向您说明基本知识。

票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/23794815

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档