Created
August 31, 2018 12:51
-
-
Save edwardstock/a30dfc52a5dfe524dee41e94ffe73e35 to your computer and use it in GitHub Desktop.
Android Decimal Number Input Filter
This file contains 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
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