我在使用addonTextChangeListener时得到了StackOverflowError

时间:2015-05-01 05:35:06

标签: android

我有两个EditText editText1和editText2 应该发生:当用户一次写入editText1时,输入editText1的值应该乘以6,而editText2则得到该结果,反之亦然。 发生的事情:当我写入editText1或editText2时,它会崩溃(stackOverFlowError)。 对于上面的scenariyo我正在使用addTextChangeListener。

3 个答案:

答案 0 :(得分:1)

这是因为您正在侦听 onTextChangeListener ,并根据用户的输入,然后您正在更改另一个edittext的值,再次调用 onTextChangeListener ,然后您正在听它并再次更改edit text的值(永不结束循环)。

基本上你在这里进入永无止境的循环:)

解决方案: - 您必须有一个布尔标志,当您更改EditText的文本时应将其设置为true,并且在onTextChangeListener中您必须检查此文本是由代码还是由用户更改。如果按代码,则不采取行动。

答案 1 :(得分:1)

在我给你一个有效的答案之前。我给你一个建议,请先发表stackoverflow常见问题解答,并在发帖前先研究一下这个网站的基础知识。因为我们想知道你到目前为止所尝试的内容想回答你的问题。所以请遵循指南。

在这种情况下,我明白了,你想要的是什么,这就是解决方案。

而且AAnkit也说它变成了一个永无止境的循环

//First initialize the EditText and addTextChangedListener like shown below.
    editText1.addTextChangedListener(new TextWatcher() {@Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {}
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count,
                    int after) {}
            @Override
            public void afterTextChanged(Editable s) {
            //Before changing the text inside the EditText you want to remove the text change listener.
                editText1.removeTextChangedListener(this);
            //Here you make the changes to EditText
                editText1.setText("hi");
            //After changing the content of the EditText you want to register the text change listener.
                editText1.addTextChangedListener(this);
            }
        });

希望你能得到答案。

这里是对这个答案的详细描述。

http://www.revealedtricks4u.com/2015/05/how-to-change-text-of-edittext-inside.html

我礼貌地要求你遵循以后的SO指南。

答案 2 :(得分:0)

因为正在连续调用onTextChangeListener。 EditText1更新编辑文本2的文本并编辑editText1的文本更新文本。因此onTextChangeListener被无限次调用。