What I'm trying to do is limit the range of values that can be inserted in a EditText, like a NumberPicker. Why won't I use NumberPicker? Because it needs API 11 and I'm want my application to be compatible with API 10 and above. I have set the range from 1 to 120. If a user enters a number outside that range, the text in the EditText will change to 15.
I have this code that works however I think it's not the best way to implement this.
final EditText ed = ((EditText) findViewById(R.id.editMinutes));
TextWatcher tw = new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void afterTextChanged(Editable s) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
try {
int minutes = Integer.valueOf(s.toString());
if (minutes < 1 || minutes > 120) {
ed.setText("15");
}
} catch (NumberFormatException ex) {
ed.setText("15");
}
}
};
ed.addTextChangedListener(tw);
How can I improve this? Is there a better or more elegant way of doing this?