Restricting text editing in android with decimal point
I have a question about the limit number in editText. I want the user to only be able to enter a number between 1-70. When a user wants to bet 70.01 or more, I want them not to be allowed. Only two decimal places are allowed. The total length is 5 characters, including the period.
I can limit before and after the decimal. and also limit 70, but user can enter 70.99 (not sure why) in a text editor that I want to block. my validation works when user enters 71 or more
this is the constructor i im using in the fragment
txtno.setFilters(new InputFilter[] {new DecimalDigitsInputFilter(Integer.parseInt(getString(R.string.length)),2,txtno)});
this is the value after and before the decimal number
@Override
public CharSequence filter(CharSequence source, int start, int end,Spanned dest, int dstart, int dend) {
mTextView.setKeyListener(DigitsKeyListener.getInstance(true,true));
String etText = mTextView.getText().toString();
String temp = mTextView.getText() + source.toString();
if (temp.equals(".")) {
return "0.";
} else if (temp.toString().indexOf(".") == -1) {
// no decimal point placed yet
if (temp.length() > mMyint) {
return "";
}
} else {
int dotPosition;
int cursorPositon = mTextView.getSelectionStart();
if (etText.indexOf(".") == -1) {
dotPosition = temp.indexOf(".");
} else {
dotPosition = etText.indexOf(".");
}
if (cursorPositon <= dotPosition) {
String beforeDot = etText.substring(0, dotPosition);
if (beforeDot.length() < mMyint) {
return source;
} else {
if (source.toString().equalsIgnoreCase(".")) {
return source;
} else {
return "";
}
}
} else {
temp = temp.substring(temp.indexOf(".") + 1);
if (temp.length() > mMydec) {
return "";
}
}
}
return null;
}
& this is a textWatcher for a limit of 70
public void afterTextChanged(Editable s) {
try{
if(Integer.parseInt(s.toString())>70){
s.replace(0, s.length(), s.toString());
}
}catch(Exception e){}
Thanks in advance.
+3
source to share