Skip to content

Instantly share code, notes, and snippets.

@tokudu
Created October 12, 2016 04:52
Show Gist options
  • Save tokudu/e9016cf8389cfe7c7a2d177c5732dc19 to your computer and use it in GitHub Desktop.
Save tokudu/e9016cf8389cfe7c7a2d177c5732dc19 to your computer and use it in GitHub Desktop.
TextWatcher for formatting SSN as XXX-XX-XXXX
import android.text.Editable;
import android.text.TextWatcher;
import android.widget.EditText;
public class SSNFormattingTextWatcher implements TextWatcher {
private EditText mEditText;
private boolean mShouldDeleteSpace;
public SSNFormattingTextWatcher(EditText editText) {
mEditText = editText;
}
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
if (start > 0) {
CharSequence charDeleted = s.subSequence(start - 1, start);
mShouldDeleteSpace = "-".equals(charDeleted.toString());
}
}
public void afterTextChanged(Editable editable) {
mEditText.removeTextChangedListener(this);
int cursorPosition = mEditText.getSelectionStart();
String withSpaces = formatText(editable);
mEditText.setText(withSpaces);
mEditText.setSelection(cursorPosition + (withSpaces.length() - editable.length()));
if (mShouldDeleteSpace) {
// userNameET.setSelection(userNameET.getSelectionStart() - 1);
mShouldDeleteSpace = false;
}
mEditText.addTextChangedListener(this);
}
private String formatText(CharSequence text) {
StringBuilder formatted = new StringBuilder();
if (text.length() == 4 || text.length() == 7) {
if (!mShouldDeleteSpace) {
formatted.append(text.subSequence(0, text.length() - 1) + "-" + text.charAt(text.length() - 1));
} else {
formatted.append(text.subSequence(0, text.length() - 1));
}
} else {
formatted.append(text);
}
return formatted.toString();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment