这里有新的SO用户,对Java来说还很陌生。运行此命令后,它会崩溃并出现java.lang.stackoverflow错误。我可以肯定它是递归的,但我不知道为什么。我试着逐步调试,但收到一个错误,提示它找不到类文件。这是代码:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
newPrice.addTextChangedListener(tradeWatch);
tradeIn.addTextChangedListener(tradeWatch);
acc.addTextChangedListener(tradeWatch);
tradeDif.addTextChangedListener(tradeWatch);
}
TextWatcher tradeWatch = new TextWatcher() {
@Override
public void afterTextChanged(Editable s) {
calcTrade();
}
@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
}
};
private void calcTrade() {
Editable eValue1 = newPrice.getText(), eValue2 = tradeIn.getText(), eValue3 = acc.getText();
Double value1 = 0.0, value2 = 0.0, value3 = 0.0, result = 0.0;
if (eValue1 != null)
value1 = toDouble(eValue1);
if (eValue2 != null)
value2 = toDouble(eValue2);
if (eValue3 != null)
value3 = toDouble(eValue3);
if (value1 != null && value2 != null && value3 != null)
result = value1 - (value2 + value3);
tradeDif.setText(result.toString());
}
private double toDouble(final Editable editable) {
final String content = editable.toString();
if (content.isEmpty()) {
return 0;
}
return Double.parseDouble(content);
}
public void nextPage(View v) {
Intent i=new Intent(this, Activity2.class);
startActivity(i);
}
}
最佳答案
问题是您的tradeDif
使用的是tradeWatch
TextWatcher。在该TextWatcher的afterTextChanged()
中,您调用calcTrade()
,后者又调用tradeDif.setText(result.toString());
。
Android完成在tradeDif
上的文本设置后,它将再次在TextWatcher上调用afterTextChanged()
,它将继续这样做,直到您停止设置tradeDif
的文本为止。