Reputation: 11
I need to enter only even numbers(range:0-20) in edittext in textwatcher. However, when i did the following, it remained same that is it is allowing both even and odd numbers to be entered. I want when a user enters an odd number the toast is displayed. guide me please!
even
@Override
public void afterTextChanged(Editable s) {
try {
int v = Integer.parseInt(s.toString());
if(v%2!=0){
if (v > 20) {
s.replace(0, s.length(), "", 0, 2);
} else if (v < 0) {
s.replace(0, s.length(), "", 0, 1);
}
}
} catch (NumberFormatException ex)
{
Toast.makeText(MainActivity.this, "invalid", Toast.LENGTH_LONG).show();
}
}
Upvotes: 1
Views: 340
Reputation: 734
You are just showing the Toast when a NumberFormatException exception is thrown, meaning that the string does not contain a number. So you have to show the toast also when the number is even, and you will do it on the else condition of
if(v%2 != 0){
//Number is odd
}else{
//Number is even
}
Try like the following:
@Override
public void afterTextChanged(Editable s)
try {
int v = Integer.parseInt(s.toString());
if(v>0 && v<20){
if(v%2 != 0){
Toast.makeText(getContext(), "ODD", Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(getContext(), "EVEN", Toast.LENGTH_SHORT).show();
}
}else{
Toast.makeText(getContext(), "OUT OF RANGE", Toast.LENGTH_SHORT).show();
}
}catch (NumberFormatException e){
Toast.makeText(getContext(), "INVALID", Toast.LENGTH_SHORT).show();
}
}
Upvotes: 2