我已经搜索了如何使用textwatcher格式化带有货币或百分号的数字,但仍然无法使用。我尝试使用DecimalFormat方法,因为它看起来很简单,但我想因为textwatch不断运行,我的应用程序崩溃了。这是我所拥有的片段。我只需要textViewproceeds.setText(addProceeds())格式化为货币或百分比。感谢。
editText1 = (EditText) findViewById(R.id.editText1);
editText2 = (EditText) findViewById(R.id.editText2);
editText3 = (EditText) findViewById(R.id.editText3);
editText1.addTextChangedListener(new TextWatcher() {
boolean editing = false;
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
// TODO Auto-generated method stub
}
public void onTextChanged(CharSequence s, int start, int before,
int count) {
}
public void afterTextChanged(Editable s) {
// TODO Auto-generated method stub
if(!editing) {
editing = true;
editText1.removeTextChangedListener(this);
editText3.setText(currency.format(Double.parseDouble(addProceeds())));
editText1.addTextChangedListener(this);
editing = false;
}
}
});
editText2.addTextChangedListener(new TextWatcher() {
boolean editing = false;
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
// TODO Auto-generated method stub
}
public void onTextChanged(CharSequence s, int start, int before,
int count) {
}
public void afterTextChanged(Editable s) {
// TODO Auto-generated method stub
if(!editing) {
editing = true;
editText1.removeTextChangedListener(this);
editText3.setText(currency.format(Double.parseDouble(addProceeds())));
editText1.addTextChangedListener(this);
editing = false;
}
}
});
}
private String addProceeds() {
Double num1;
Double num2;
if (editText1.getText().toString() != "" && editText1.getText().length() > 0) {
num1 = Double.parseDouble("0" + editText1.getText().toString());
} else {
num1 = Double.valueOf(0);
}
if (editText2.getText().toString() != "" && editText2.getText().length() > 0) {
num2 = Double.parseDouble("0" + editText2.getText().toString());
} else {
num2 = Double.valueOf(0);
}
return Double.toString(num1 + num2);
}
到目前为止,以下格式作为单个editText字段的最终计算格式正常,但由于无限循环而输入数字时不起作用。
//Put below somewhere at class level
DecimalFormat currency = new DecimalFormat("$###,##0.00");
boolean editing = false;
public void afterTextChanged(Editable s) {
// TODO Auto-generated method stub
if(!editing) {
editing = true;
editText1.removeTextChangedListener(this);
editText3.setText(currency.format(Double.parseDouble(addProceeds())));
editText1.addTextChangedListener(this);
editing = false;
}