我需要在textwatcher的edittext中输入偶数(范围:0-20)。但是,当我执行以下操作时,它保持相同,即允许输入偶数和奇数。我想当用户输入奇数时显示吐司。请指导我!
甚至
@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();
}
}
答案 0 :(得分:2)
当抛出NumberFormatException异常时,您只是显示Toast,这意味着该字符串不包含数字。 所以你必须在数字是偶数时展示吐司,你将在
的其他条件下进行if(v%2 != 0){
//Number is odd
}else{
//Number is even
}
尝试以下内容:
@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();
}
}