Last active
August 29, 2015 14:06
-
-
Save fhur/06c9c74033cce14eb08e to your computer and use it in GitHub Desktop.
EditText that auto formats it's content in a readable way. Numbers are formatted like this: 1234567890 => 123-456-7890
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
/** | |
* {@link TextView} that displays only numbers, formated as a readable phone number. | |
* Example: 123-234-3456 instead of 1232343456 | |
* | |
* @author fernandohur | |
*/ | |
public class PhoneEditText extends EditText implements TextWatcher { | |
private boolean ignoreTextChange; | |
public PhoneEditText(Context context, AttributeSet attrs) { | |
super(context, attrs); | |
addTextChangedListener(this); | |
ignoreTextChange = false; | |
} | |
/** | |
* Given a string containing only numbers and '-', {@link #applyPhoneFormat(String)} will | |
* return a formated phone number. If characters different than numbers or '-' are contained in the parameter | |
* this method does not guarantee a correct result. | |
* | |
* @param phone a string containing only numbers and "-" | |
* @return a formated phone string | |
*/ | |
public String applyPhoneFormat(String phone) { | |
phone = phone.replace("-", ""); | |
int size = phone.length(); | |
if (size <= 4) { | |
return phone; | |
} else { | |
StringBuilder builder = new StringBuilder(); | |
for (int i = phone.length() - 1; i >= 0; i--) { | |
if (i > phone.length() - 4 - 1) { | |
builder.append(phone.charAt(i)); | |
} else if (i == phone.length() - 4) { | |
builder.append("-"); | |
builder.append(phone.charAt(i)); | |
} else { | |
if ((builder.length() - 4) % 4 == 0) { | |
builder.append("-"); | |
} | |
builder.append(phone.charAt(i)); | |
} | |
} | |
return builder.reverse().toString(); | |
} | |
} | |
public boolean matchesFormatedPhoneNumber(String phone) { | |
String regex1 = "[0-9]{1,4}"; | |
String regex2 = "[0-9]{1,3}-[0-9]{4}"; | |
String regex3 = "[0-9]{1,3}(-[0-9]{3}){1,}-[0-9]{4}"; | |
return phone.matches(regex1) || phone.matches(regex2) || phone.matches(regex3); | |
} | |
@Override | |
public void onTextChanged(CharSequence text, int start, int lengthBefore, int lengthAfter) { | |
super.onTextChanged(text, start, lengthBefore, lengthAfter); | |
} | |
@Override | |
public void afterTextChanged(Editable s) { | |
String phone = s.toString(); | |
if (!ignoreTextChange) { | |
String formatedPhone = applyPhoneFormat(phone); | |
ignoreTextChange = true; | |
setText(formatedPhone); | |
if (formatedPhone.length() > 0) | |
setSelection(formatedPhone.length()); | |
ignoreTextChange = false; | |
} | |
} | |
@Override | |
public void beforeTextChanged(CharSequence s, int start, int count, int after) { | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment