EditText中TextWatcher观察器中的StackOverflow错误

时间:2014-02-06 10:29:29

标签: java android android-edittext stack-overflow textwatcher

我正在将我的金额文本从EditText转换为双重格式,并且我尝试删除","中的EditText以执行我的计算的正确格式。我的代码有什么问题,堆栈溢出了?

// Gets the two EditText controls' Editable values

String cleanBasicTax;
if(txtBasicTax.getText().toString().contains(",")){
    cleanBasicTax=txtBasicTax.getText().toString().replace(",", "");
}
else{
    cleanBasicTax=txtBasicTax.getText().toString();
}

String cleantxtSurcharge;
if(txtSurcharge.getText().toString().contains(",")){
    cleantxtSurcharge=txtSurcharge.getText().toString().replace(",", "");
}
else{
    cleantxtSurcharge=txtSurcharge.getText().toString();
}

String cleanInterest;
if(txtInterest.getText().toString().contains(",")){
    cleanInterest=txtInterest.getText().toString().replace(",", "");
}
else{
    cleanInterest=txtInterest.getText().toString();
}

String cleanCompromise=txtCompromise.getText().toString().replace(",", "");
if(txtCompromise.getText().toString().contains(",")){
    cleanCompromise=txtCompromise.getText().toString().replace(",", "");
}
else{
    cleanCompromise=txtCompromise.getText().toString();
}           

Editable editableValueBasicTax = txtBasicTax.getText().replace(0, txtBasicTax.length(), cleanBasicTax),
    editableValueSurcharge = txtSurcharge.getText().replace(0, txtSurcharge.length(), cleantxtSurcharge),
    editableValueInterest = txtInterest.getText().replace(0, txtInterest.length(), cleanInterest),
    editableValueCompromise = txtCompromise.getText().replace(0, txtCompromise.length(), cleanCompromise);

2 个答案:

答案 0 :(得分:4)

你的TextWathcer更改了正在观看的文本,导致另一个观察者的调用,导致文本的另一个更改,......等等,直到你用完堆栈空间调用方法。

解决这个问题的一种方法是在观察者内部运行时向boolean设置true标志,如果标志设置为终止递归,则立即返回。在伪代码中:

boolean mIsInWatcher = false;

void onTextChanged(...) {
   if (mIsInWatcher) return;
   mIsInWatcher = true;

   // text modifications here

   mIsInWatcher = false;
}

答案 1 :(得分:2)

如果要调用textView onTextChangeListener,并在同一方法中替换文本,则只需进入循环,因为replace将调用相同的方法。因而错误。

尝试在其他地方替换文字。