Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import android.text.Editable;
- import android.text.TextWatcher;
- import android.widget.EditText;
- import java.text.DecimalFormat;
- import java.text.ParseException;
- /**
- * Created by Mina on 21/09/2015.
- */
- public class MoneyTextWatcher implements TextWatcher {
- private EditText et;
- private final DecimalFormat df ;
- private final DecimalFormat dfnd ;
- boolean hasFractionalPart;
- private int traillingZeroCount;
- public MoneyTextWatcher(EditText mEditText, String Pattern) {
- this.et = mEditText;
- df = new DecimalFormat(Pattern);
- df.setDecimalSeparatorAlwaysShown(true);
- dfnd= new DecimalFormat("#,###.00");
- hasFractionalPart = false;
- }
- @Override
- public void beforeTextChanged(CharSequence s, int start, int count, int after) {
- }
- @Override
- public void onTextChanged(CharSequence s, int start, int before, int count) {
- int index = s.toString().indexOf(String.valueOf(df.getDecimalFormatSymbols().getDecimalSeparator()));
- traillingZeroCount = 0;
- if (index > -1) {
- for (index++; index < s.length(); index++) {
- if (s.charAt(index) == '0')
- traillingZeroCount++;
- else {
- traillingZeroCount = 0;
- }
- }
- hasFractionalPart = true;
- } else {
- hasFractionalPart = false;
- }
- }
- @Override
- public void afterTextChanged(Editable s) {
- et.removeTextChangedListener(this);
- if (s != null && !s.toString().isEmpty()) {
- try {
- int inilen, endlen;
- inilen = et.getText().length();
- String v = s.toString().replace(String.valueOf(df.getDecimalFormatSymbols().getGroupingSeparator()), "").replace("$","");
- Number n = df.parse(v);
- int cp = et.getSelectionStart();
- if (hasFractionalPart) {
- StringBuilder trailingZeros = new StringBuilder();
- while (traillingZeroCount-- > 0)
- trailingZeros.append('0');
- et.setText(df.format(n) + trailingZeros.toString());
- } else {
- et.setText(dfnd.format(n));
- }
- et.setText("$".concat(et.getText().toString()));
- endlen = et.getText().length();
- int sel = (cp + (endlen - inilen));
- if (sel > 0 && sel < et.getText().length()) {
- et.setSelection(sel);
- } else if (traillingZeroCount > -1) {
- et.setSelection(et.getText().length() - 3);
- } else {
- et.setSelection(et.getText().length());
- }
- } catch (NumberFormatException | ParseException e) {
- e.printStackTrace();
- }
- }
- et.addTextChangedListener(this);
- }
- }
Add Comment
Please, Sign In to add comment