是的,这很有可能,即使您不必分别管理“$”和小数.
下面是TextWatcher操作的简单EditText:
final EditText editText = (EditText) findViewById(R.id.edt);
editText.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence charSequence,int i,int i1,int i2) {
}
@Override
public void onTextChanged(CharSequence charSequence,int i2) {
}
@Override
public void afterTextChanged(Editable editable) {
if (editText == null) return;
String inputString = editable.toString();
editText.removeTextChangedListener(this);
String cleanString = inputString.toString().replaceAll("[$,.]","");
BigDecimal bigDecimal = new BigDecimal(cleanString).setScale(2,BigDecimal.ROUND_FLOOR).divide(new BigDecimal(100),BigDecimal.ROUND_FLOOR);
String converted = NumberFormat.getCurrencyInstance().format(bigDecimal);
editText.setText(converted);
editText.setSelection(converted.length());
editText.addTextChangedListener(this);
}
});
如果您需要知道如何在xml中创建EditText,请执行以下操作:
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/edt"
android:inputType="numberDecimal"
android:textDirection="anyRtl"
android:gravity="right"/>
这是一个老问题,但也许,最好回答:)