有办法为Android中的EditText定义min和max值吗?我想为EditText.例如:如果任何人试图在其中输入一个月值,则该值必须介于1-12之间。我可以用TextWatcher但我想知道在布局文件或其他地方是否有其他方法可以做到这一点。编辑:我不想限制字符计数。我想限制价值。例如,如果我限制月份EditText当我输入12个字符时,它会接受它,但是如果我输入了22个字符,它就不能在我进入的时候接受它。
3 回答
互换的青春
TA贡献1797条经验 获得超6个赞
min==3
min>=10
EditText
InputFilterMinMax
InputFilter
OnFocusChangeListener
EditText
package test;import android.text.InputFilter;import android.text.Spanned;public class InputFilterMax implements InputFilter {private int max;public InputFilterMax(int max) { this.max = max;}public InputFilterMax(String max) { this.max = Integer.parseInt(max);}@Overridepublic CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) { try { String replacement = source.subSequence(start, end).toString(); String newVal = dest.toString().substring(0, dstart) + replacement +dest.toString().substring(dend, dest.toString().length()); int input = Integer.parseInt(newVal); if (input<=max) return null; } catch (NumberFormatException nfe) { } //Maybe notify user that the value is not good return "";}}
OnFocusChangeListenerMin
package test;import android.text.TextUtils;import android.view.View;import android.view.View.OnFocusChangeListener;public class OnFocusChangeListenerMin implements OnFocusChangeListener {private int min;public OnFocusChangeListenerMin(int min) { this.min = min;}public OnFocusChangeListenerMin(String min) { this.min = Integer.parseInt(min);}@Overridepublic void onFocusChange(View v, boolean hasFocus) { if(!hasFocus) { String val = ((EditText)v).getText().toString(); if(!TextUtils.isEmpty(val)){ if(Integer.valueOf(val)<min){ //Notify user that the value is not good } } }}}
InputFilterMax
OnFocusChangeListenerMin
EditText
onFocusChangeListener
.
mQteEditText.setOnFocusChangeListener( new OnFocusChangeListenerMin('20');mQteEditText.setFilters(new InputFilter[]{new InputFilterMax(getActivity(),'50')});
- 3 回答
- 0 关注
- 671 浏览
添加回答
举报
0/150
提交
取消