Skip to content

Instantly share code, notes, and snippets.

@edwardstock
Created August 31, 2018 12:51
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 edwardstock/a30dfc52a5dfe524dee41e94ffe73e35 to your computer and use it in GitHub Desktop.
Save edwardstock/a30dfc52a5dfe524dee41e94ffe73e35 to your computer and use it in GitHub Desktop.
Android Decimal Number Input Filter
public class DecimalInputFilter extends android.text.method.DigitsKeyListener {
private final WeakReference<EditText> mView;
private int mDecimals = 18;
public DecimalInputFilter(EditText txtView) {
this(txtView, 18);
}
public DecimalInputFilter(EditText txtView, int decimals) {
super(false, true);
mView = new WeakReference<>(txtView);
mDecimals = decimals;
}
@Override
public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
String tmp = mView.get().getText().toString();
if (source.equals(",")) {
return "";
}
if (source.equals(".") && tmp.isEmpty()) {
return "0.";
}
if (tmp.equals("0") && !source.equals(".")) {
return "";
}
if (source.equals(".") && tmp.contains(".")) {
return "";
}
final int ptIndex = tmp.indexOf(".");
if (ptIndex == -1) {
if (tmp.equals("0") && source.equals(".")) {
return source;
}
if (tmp.length() > 0 && ((tmp.charAt(0) == '0' && dstart > 0) || (tmp.charAt(0) != '0' && source.equals("0") && dstart == 0))) {
return "";
}
return source;
}
if (ptIndex >= dstart) {
if (tmp.charAt(0) == '.') {
return source;
}
if ((tmp.charAt(0) == '0' && dstart > 0) || (tmp.charAt(0) != '0' && source.equals("0") && dstart == 0)) {
return "";
}
} else if (ptIndex < dstart) {
String decimals = tmp.substring(ptIndex + 1);
if (decimals.length() >= mDecimals) {
return "";
}
}
return super.filter(source, start, end, dest, dstart, dend);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment