Last active
August 29, 2015 14:05
-
-
Save malvre/8508d2330f806cf32c93 to your computer and use it in GitHub Desktop.
[Android] CurrencyTextWatcher
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Usage: | |
txtValor.addTextChangedListener(new CurrencyTextWatcher(txtValor)); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class Currency { | |
public static String toString(double value) { | |
DecimalFormat formatter = (DecimalFormat) NumberFormat.getCurrencyInstance(); | |
DecimalFormatSymbols symbols = formatter.getDecimalFormatSymbols(); | |
symbols.setCurrencySymbol(""); | |
formatter.setDecimalFormatSymbols(symbols); | |
return formatter.format(value); | |
} | |
public static String toString(String value) { | |
double parsed = Double.parseDouble(value); | |
return Currency.toString(parsed); | |
} | |
public static double toDouble(String strValue) { | |
String cleanString = strValue.replaceAll("[,.]", ""); | |
return Double.parseDouble(cleanString)/100; | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class CurrencyTextWatcher implements TextWatcher { | |
private String current = ""; | |
EditText editText; | |
public CurrencyTextWatcher(EditText editText) { | |
this.editText = editText; | |
} | |
@Override | |
public void beforeTextChanged(CharSequence s, int start, int count, int after) { | |
} | |
@Override | |
public void onTextChanged(CharSequence s, int start, int before, int count) { | |
if(!s.toString().equals(current)){ | |
editText.removeTextChangedListener(this); | |
double parsed = Currency.toDouble(s.toString()); | |
String formatted = Currency.toString(parsed); | |
current = formatted; | |
editText.setText(formatted); | |
editText.setSelection(formatted.length()); | |
editText.addTextChangedListener(this); | |
} | |
} | |
@Override | |
public void afterTextChanged(Editable s) { | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment