Ok, aquí hay una mejor manera de lidiar con los formatos de moneda, pulsación de tecla eliminar-retroceder. El código se basa en el código @androidcurious 'anterior ... Pero, trata algunos problemas relacionados con la eliminación hacia atrás y algunas excepciones de análisis:
http://miguelt.blogspot.ca/2013/01/textwatcher-for-currency-masksformatting .html
[ACTUALIZAR] La solución anterior tenía algunos problemas ... Esta es una mejor solución: http://miguelt.blogspot.ca/2013/02/update-textwatcher-for-currency.html
Y ... aquí están los detalles:
Este enfoque es mejor ya que utiliza los mecanismos convencionales de Android. La idea es formatear valores después de que el usuario exista la Vista.
Defina un InputFilter para restringir los valores numéricos; esto es necesario en la mayoría de los casos porque la pantalla no es lo suficientemente grande para acomodar vistas de EditText largas. Esta puede ser una clase interna estática o simplemente otra clase simple:
class NumericRangeFilter implements InputFilter {
private final double maximum;
private final double minimum;
NumericRangeFilter() {
this(0.00, 999999.99);
}
NumericRangeFilter(double p_min, double p_max) {
maximum = p_max;
minimum = p_min;
}
@Override
public CharSequence filter(
CharSequence p_source, int p_start,
int p_end, Spanned p_dest, int p_dstart, int p_dend
) {
try {
String v_valueStr = p_dest.toString().concat(p_source.toString());
double v_value = Double.parseDouble(v_valueStr);
if (v_value<=maximum && v_value>=minimum) {
return null;
}
} catch (NumberFormatException p_ex) {
}
return "";
}
}
Defina una clase (estática interna o simplemente una clase) que implementará View.OnFocusChangeListener. Tenga en cuenta que estoy usando una clase de utilidades; la implementación se puede encontrar en "Cantidades, impuestos".
class AmountOnFocusChangeListener implements View.OnFocusChangeListener {
@Override
public void onFocusChange(View p_view, boolean p_hasFocus) {
EditText v_amountView = (EditText)p_view;
if (p_hasFocus) {
String v_value = v_amountView.getText().toString();
int v_cents = Utils.parseAmountToCents(v_value);
v_value = Utils.formatCentsToAmount(v_cents);
v_amountView.setText(v_value);
v_amountView.selectAll();
} else {
String v_value = v_amountView.getText().toString();
int v_cents = Utils.parseAmountToCents(v_value);
v_value = Utils.formatCentsToCurrency(v_cents);
v_amountView.setText(v_value);
}
}
}
Esta clase eliminará el formato de moneda al editar, basándose en mecanismos estándar. Cuando el usuario sale, se vuelve a aplicar el formato de moneda.
Es mejor definir algunas variables estáticas para minimizar el número de instancias:
static final InputFilter[] FILTERS = new InputFilter[] {new NumericRangeFilter()};
static final View.OnFocusChangeListener ON_FOCUS = new AmountOnFocusChangeListener();
Finalmente, dentro de onCreateView (...):
EditText mAmountView = ....
mAmountView.setFilters(FILTERS);
mAmountView.setOnFocusChangeListener(ON_FOCUS);
Puede reutilizar FILTERS y ON_FOCUS en cualquier número de vistas de EditText.
Aquí está la clase Utils:
public class Utils {
private static final NumberFormat FORMAT_CURRENCY = NumberFormat.getCurrencyInstance();
public static int parseAmountToCents(String p_value) {
try {
Number v_value = FORMAT_CURRENCY.parse(p_value);
BigDecimal v_bigDec = new BigDecimal(v_value.doubleValue());
v_bigDec = v_bigDec.setScale(2, BigDecimal.ROUND_HALF_UP);
return v_bigDec.movePointRight(2).intValue();
} catch (ParseException p_ex) {
try {
BigDecimal v_bigDec = new BigDecimal(p_value);
v_bigDec = v_bigDec.setScale(2, BigDecimal.ROUND_HALF_UP);
return v_bigDec.movePointRight(2).intValue();
} catch (NumberFormatException p_ex1) {
return -1;
}
}
}
public static String formatCentsToAmount(int p_value) {
BigDecimal v_bigDec = new BigDecimal(p_value);
v_bigDec = v_bigDec.setScale(2, BigDecimal.ROUND_HALF_UP);
v_bigDec = v_bigDec.movePointLeft(2);
String v_currency = FORMAT_CURRENCY.format(v_bigDec.doubleValue());
return v_currency.replace(FORMAT_CURRENCY.getCurrency().getSymbol(), "").replace(",", "");
}
public static String formatCentsToCurrency(int p_value) {
BigDecimal v_bigDec = new BigDecimal(p_value);
v_bigDec = v_bigDec.setScale(2, BigDecimal.ROUND_HALF_UP);
v_bigDec = v_bigDec.movePointLeft(2);
return FORMAT_CURRENCY.format(v_bigDec.doubleValue());
}
}