Skip to content

Instantly share code, notes, and snippets.

@huttneab
Created July 1, 2014 20:00
Show Gist options
  • Save huttneab/5a902104d8e6cd0d93d4 to your computer and use it in GitHub Desktop.
Save huttneab/5a902104d8e6cd0d93d4 to your computer and use it in GitHub Desktop.
private static final String PERCENT_PATTERN = "((^[0]$)|(^[1-9]\\d*$))";
TextWatcher mTextWatcher = new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence charSequence, int i, int i2, int i3) {
}
@Override
public void onTextChanged(CharSequence charSequence, int i, int i2, int i3) {
if (!charSequence.toString().matches(PERCENT_PATTERN)) {
String userInput = "" + charSequence.toString().replaceAll("[^\\d]", "");
userInput = userInput.replaceAll("^0+(?!$)","");
if(userInput.isEmpty()){
userInput = "0";
}
mTipView.setText(userInput);
// keeps the cursor always to the right
Selection.setSelection(mTipView.getText(), userInput.length());
}
}
@Override
public void afterTextChanged(Editable editable) {
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment