Skip to content

Instantly share code, notes, and snippets.

@senneco
Last active November 8, 2016 06:47
Show Gist options
  • Save senneco/8b5a8e7974fb145c5b277fcf4a7b451b to your computer and use it in GitHub Desktop.
Save senneco/8b5a8e7974fb145c5b277fcf4a7b451b to your computer and use it in GitHub Desktop.
This watchers format entered value as # ###,##. Backspace working right every time
public class Watcher implements TextWatcher {
private static final char THOUSANDS_SEPARATOR = ' ';
private static final char FRACTION_SEPARATOR = ',';
private boolean mIsSpaceRemoved;
private int mRemovedSpacePosition;
private EditText mValueEditText;
private InputFilter[] mFilters;
public Watcher(EditText valueEditText) {
mValueEditText = valueEditText;
mFilters = mValueEditText.getFilters();
}
@Override
public void beforeTextChanged(CharSequence charSequence, int start, int count, int after) {
if (start > 0 && count == 1) {
mIsSpaceRemoved = charSequence.charAt(start) == THOUSANDS_SEPARATOR;
if (mIsSpaceRemoved) {
mRemovedSpacePosition = start;
}
}
}
@Override
public void onTextChanged(CharSequence charSequence, int start, int before, int count) {
}
@Override
public void afterTextChanged(Editable editable) {
if (mIsSpaceRemoved) {
mIsSpaceRemoved = false;
editable.replace(mRemovedSpacePosition - 1, mRemovedSpacePosition, "");
}
mValueEditText.removeTextChangedListener(this);
mValueEditText.setFilters(new InputFilter[]{});
int position = -1;
for (int i = 0; i < editable.length(); i++) {
if (editable.charAt(i) == THOUSANDS_SEPARATOR) {
editable.replace(i, i + 1, "");
i--;
continue;
}
if (editable.charAt(i) == FRACTION_SEPARATOR) {
if (position >= 0) {
editable.replace(position, position + 1, "");
}
position = i;
}
}
if (position != -1 && position + 3 < editable.length()) {
editable.replace(position + 3, editable.length(), "");
}
position = position != -1 ? position : editable.length();
for (int i = position - 3; i >= 0; i = i - 3) {
editable.insert(i, String.valueOf(THOUSANDS_SEPARATOR));
}
mValueEditText.setFilters(mFilters);
mValueEditText.addTextChangedListener(this);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment