gpt4 book ai didi

android - 导致 stackOverflow 的 TextWatcher

转载 作者:行者123 更新时间:2023-11-29 21:08:17 25 4
gpt4 key购买 nike

基本上,我有一个 Editable(在本例中是一个 TextView),它有一个 TextChangedListener(一个 TextWatcher),我的问题是当在 TextWatcher< 的 afterTextChanged 回调中编辑它时,如何导致 stackOverflow/?

一些代码

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) {}
});
}

最佳答案

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

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) {

}
});
}

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

关于android - 导致 stackOverflow 的 TextWatcher,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23794815/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com