我正在尝试创建一个简单的货币转换器,并按照 Google 的货币转换器对其进行建模,用户将在一个字段中输入金额,应用程序将在相应字段中转换并显示该金额。
为此,我决定使用 onTextChanged
监听器,因为我希望它在用户输入金额时进行更新。
这里有一些代码 fragment ,可以让您更清晰地了解情况。
private EditText Dollar,Euro;
private double Result;
private String Amount,Amount2;
Dollar=(EditText)findViewById(R.id.tbDollar);
Euro=(EditText)findViewById(R.id.tbEuro);
Dollar.addTextChangedListener(new TextWatcher()
{
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
try
{
Euro.setText(" ");
Amount=Dollar.getText().toString();
Result=0.92*Double.parseDouble(Amount);
Amount2 = String.format("%.2f", Result);
Euro.setText(Amount2);
}
catch (Exception e)
{
Euro.setText("0.00");
Log.e("Error","Unable to convert a blank Number");
}
}
这段代码一直工作得很好,直到我为欧元字段添加了相同的代码,添加后,当输入任何数字时,应用程序就会崩溃。
我确实怀疑,例如,当将一个数字插入美元字段时,它会计算欧元并将其插入欧元字段,然后触发欧元的 onTextchanged
监听器,计算美元并尝试将其插入那里,几乎创建了一个无限循环,然后使应用程序崩溃。
我确实认为解决方案是指定 onTextChanged
监听器仅从用户输入触发,但我无法找到有关该主题的任何内容。
出于兴趣考虑,包含了 Euro onTextChanged
监听器,并且所有这些代码都在 OnCreate 方法中声明(如果有任何区别)。
谢谢
public void onTextChanged(CharSequence s, int start, int before, int count)
{
try
{
Amount=Euro.getText().toString();
Result=1.09*Double.parseDouble(Amount);
Amount2 = String.format("%.2f", Result);
Dollar.setText(Amount2);
}
catch (Exception e)
{
Dollar.setText("0.00");
Log.e("Error","Unable to convert a blank Number");
}
}
最佳答案
在各自的 onTextChanged 监听器中检查编辑文本的焦点。如果编辑文本没有聚焦,只需在 try catch block 之前返回即可。
关于java - 使用两个 onTextChanged 监听器(Android),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35770766/