Here is a scenario where I want the user to prevent from adding numbers after point and before of a decimal number.
Example
a)Max char before point 5 and max char after point 2
—Valid numbers
1] 12345
2] 12334.0
3] 23444.55
4] .55
5] 0.5
—Invalid Numbers
1] 43242342
2] 34.45534
etc
Hope you understood what the below code is written for
Solution :
You have to add a TextWatcher for the EditText you want to put this restriction
Here is how you implement the TextWatcher class
public class DecimalTextWacher implements TextWatcher{
boolean matched=true;
CharSequence s = null;
Matcher m =null;
@Override
public void afterTextChanged(Editable s) {
if(s.length()==0)
return;
if(matched == false){
if(Pattern.matches("\\d{6}", s)||Pattern.matches("\\d{0,5}[.]\\d{3}", s)){
s.delete(s.length()-1, s.length());
}else if(Pattern.matches("\\d{6}[.]\\d{0,2}",s)){
s.delete(5,6);
}
}
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
// TODO Auto-generated method stub
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
// TODO Auto-generated method stub
Log.i("char entered", ""+s);
if(Pattern.matches("\\d{1,5}",s)==true){
Pattern p = Pattern.compile("\\d{1,5}");
m = p.matcher(s);
//check weather there is anything after 5 digits - if there it should be only a point
if(Pattern.matches("[.]?\\d{0}",s.subSequence(m.regionEnd(),s.length()))){
Log.i("matched", ""+s);
matched=true;
}
}else if(Pattern.matches("\\d{1,5}[.]\\d{0,2}",s)==true){
Log.i("matched", ""+s);
matched=true;
}else{
matched=false;
}
}
}

Follow Me!