Skip to content

Instantly share code, notes, and snippets.

@blehr
Created August 20, 2018 22:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save blehr/a7b7c606e0176a6ae59da399cc593688 to your computer and use it in GitHub Desktop.
Save blehr/a7b7c606e0176a6ae59da399cc593688 to your computer and use it in GitHub Desktop.
package com.blehr.datepickerexample;
import android.text.Editable;
import android.text.TextWatcher;
import java.util.Locale;
public class SsnMask implements TextWatcher {
private static final int MAX_LENGTH = 9;
private static final int MIN_LENGTH = 3;
private String updatedText;
private boolean editing;
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence text, int start, int before, int count) {
if (text.toString().equals(updatedText) || editing) return;
String digits = text.toString().replaceAll("\\D", "");
int length = digits.length();
if (length <= MIN_LENGTH) {
updatedText = digits;
return;
}
if (length > MAX_LENGTH) {
digits = digits.substring(0, MAX_LENGTH);
}
if (length <= 5) {
String firstPart = digits.substring(0, 3);
String secondPart = digits.substring(3);
updatedText = String.format(Locale.US, "%s-%s", firstPart, secondPart);
}
else {
String firstPart = digits.substring(0, 3);
String secondPart = digits.substring(3, 5);
String thirdPart = digits.substring(5);
updatedText = String.format(Locale.US, "%s-%s-%s", firstPart, secondPart, thirdPart);
}
}
@Override
public void afterTextChanged(Editable editable) {
if (editing) return;
editing = true;
editable.clear();
editable.insert(0, updatedText);
editing = false;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment