Created
February 8, 2016 22:49
-
-
Save abbas-oveissi/4316fd66b9aa99906df9 to your computer and use it in GitHub Desktop.
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 NumberTextWatcher implements TextWatcher { | |
//usage | |
//editText.addTextChangedListener(new NumberTextWatcher(editText)); | |
private DecimalFormat df; | |
private DecimalFormat dfnd; | |
private boolean hasFractionalPart; | |
private EditText et; | |
public NumberTextWatcher(EditText et) | |
{ | |
df = new DecimalFormat("#,###.##"); | |
df.setDecimalSeparatorAlwaysShown(true); | |
dfnd = new DecimalFormat("#,###"); | |
this.et = et; | |
hasFractionalPart = false; | |
} | |
@SuppressWarnings("unused") | |
private static final String TAG = "NumberTextWatcher"; | |
@Override | |
public void afterTextChanged(Editable s) | |
{ | |
et.removeTextChangedListener(this); | |
try { | |
int inilen, endlen; | |
inilen = et.getText().length(); | |
String v = s.toString().replace(String.valueOf(df.getDecimalFormatSymbols().getGroupingSeparator()), ""); | |
Number n = df.parse(v); | |
int cp = et.getSelectionStart(); | |
if (hasFractionalPart) { | |
et.setText(df.format(n)); | |
} else { | |
et.setText(dfnd.format(n)); | |
} | |
endlen = et.getText().length(); | |
int sel = (cp + (endlen - inilen)); | |
if (sel > 0 && sel <= et.getText().length()) { | |
et.setSelection(sel); | |
} else { | |
// place cursor at the end? | |
et.setSelection(et.getText().length() - 1); | |
} | |
} catch (NumberFormatException nfe) { | |
// do nothing? | |
} catch (ParseException e) { | |
// do nothing? | |
} | |
et.addTextChangedListener(this); | |
} | |
@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().contains(String.valueOf(df.getDecimalFormatSymbols().getDecimalSeparator()))) | |
{ | |
hasFractionalPart = true; | |
} else { | |
hasFractionalPart = false; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment