我想要做的是限制可以插入EditText的值的范围,比如NumberPicker。为什么我不使用NumberPicker?因为它需要API 11,我希望我的应用程序与API 10及更高版本兼容。 我已将范围设置为1到120.如果用户输入该范围之外的数字,EditText中的文本将更改为15.
我有这个代码可行,但我认为这不是实现此功能的最佳方式。
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);
我该如何改进?有更好或更优雅的方式吗?
答案 0 :(得分:0)
您可以使用输入过滤器来定义正则表达式
InputFilter filter= new InputFilter() {
public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
String checkMe = dest.toString()+ source.toString();
Pattern pattern = Pattern.compile("([1-9][0-9]?|1[01][0-9]|120)");
Matcher matcher = pattern.matcher(checkMe);
boolean valid = matcher.matches();
if(!valid){
Log.i("", "invalid");
return "";
}else{
Log.i("", "valid less than 120");
}
return null;
}
};
EditText editText=(EditText)findViewById(R.id.editMinutes);
editText.setFilters(new InputFilter[]{filter});
来自here
的文本观察器的更优雅代码 public abstract class TextValidator implements TextWatcher {
private final TextView textView;
public TextValidator(TextView textView) {
this.textView = textView;
}
public abstract void validate(TextView textView, String text);
@Override
final public void afterTextChanged(Editable s) {
String text = textView.getText().toString();
validate(textView, text);
}
@Override
final public void beforeTextChanged(CharSequence s, int start, int count, int after) { /* Don't care */ }
@Override
final public void onTextChanged(CharSequence s, int start, int before, int count) { /* Don't care */ }
}
像这样使用它:
editText.addTextChangedListener(new TextValidator(editText) {
@Override public void validate(TextView textView, String text) {
/* Validation code here */
}
});