Android 从 onTextChangeListener() 更改 EditText 文本

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12191394/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 09:59:26  来源:igfitidea点击:

Change EditText text from onTextChangeListener()

androidandroid-edittext

提问by sarath

I am working on an Android application.In my app I have to use images based on the text.So I write OnChangeListener()for EditText.The following is my sample code.

我正在开发一个 Android 应用程序。在我的应用程序中,我必须使用基于文本的图像。所以我写OnChangeListener()EditText。以下是我的示例代码。

edt.addTextChangedListener(this);  
@Override
public void afterTextChanged(Editable s) {
    // TODO Auto-generated method stub
    CharSequence cs=convert(edt.getText.toString());
            edt.setText(cs);
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count,
        int after) {
    // TODO Auto-generated method stub


}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
    // TODO Auto-generated method stub


}

But I am getting Exception for the above code.I know the reason for the exception is calling setText()from afterTextChanged()method. But I have to change the EditTexttext value based on the same EditTexttext change.Help me friends

但是我得到了上面代码的异常。我知道异常的原因是setText()afterTextChanged()方法调用。但是我必须EditText根据相同的EditText文本更改更改文本值。帮助我的朋友

采纳答案by Adam L. Mónos

Just simply remove your listener before you set the text, and register it again after you are done, like described here:

只需在设置文本之前删除您的侦听器,并在完成后重新注册,如下所述:

Clear EditText text after adding onTextChanged implemenation

添加 onTextChanged 实现后清除 EditText 文本

回答by Sunny

One more solution can be to use boolean variable, so that it doesn't get into infinite callstack and eventually giving stackoverflow exception

另一种解决方案是使用布尔变量,这样它就不会进入无限调用堆栈并最终给出 stackoverflow exception

public void afterTextChanged(Editable s) {
    if(!flag) 
    {
            flag = true;

            edt.setText("string");

            flag = false;
    }
}