0
我在多個editText框上有一個textwatcher,它需要計算並將結果輸出到Textview中。但是,我還需要一種方法來使用DecimalFormat,以便在用戶將其輸入到editText中後,它將它格式化爲:「$ ###,###,###。00」。我想過使用OnFocusChangedListener,但這似乎仍然會觸發afterTextChanged事件。我如何做到這一點,以便我不會結束堆棧溢出?AfterTextChanged和OnFocusChangedListener
的textwatcher稱這樣的方法:
TextWatcher Watch = new TextWatcher() {
@Override
public void afterTextChanged(Editable s) {
calc();
}
private void calc() {
Editable eValue1 = new.getText(), eValue2 = ti.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);
td.setText(formatCur(result));
}
private String formatCur(Double result) {
DecimalFormat df = new DecimalFormat("$###,###,###.00");
String format = df.format(result);
return format;
}
不知道這是否會工作。監聽器用於動態輸出計算,而不需要「計算」按鈕。如果您有任何想法,我已經發布了上面的代碼。 – 2014-11-03 19:59:00
只需添加一個私有布爾_textModifiedByWatcher = false;您在更改觀察器中的文本後將其設置爲true。在afterTextChanged你檢查_textModifiedByWatcher是否爲真。如果是,則將其設置爲false,然後立即返回。 – 2014-11-03 20:10:45
我試過這個,但有些事情不太正確。你可以添加一個簡單的例子嗎?我是新來的android和Java。 – 2014-11-05 16:38:18