在Edittext中限制范围之间的文本

时间:2014-07-09 10:22:05

标签: android android-edittext android-input-filter

我有一个edittext,我希望将该edittext中插入的数值限制在18到85之间。 我目前正在使用此InputFilter而不是我的edittext。但对我没用;

public class InputFilterMinMax implements InputFilter {

private int min, max;

public InputFilterMinMax(int min, int max) {
    this.min = min;
    this.max = max;
}

public InputFilterMinMax(String min, String max) {
    this.min = Integer.parseInt(min);
    this.max = Integer.parseInt(max);
}

@Override
public CharSequence filter(CharSequence source, int start, int end,
        Spanned dest, int dstart, int dend) {
    try {
        // Remove the string out of destination that is to be replaced
        String replacement = source.subSequence(start, end).toString();
        String newVal = dest.subSequence(0, dstart).toString()
                + replacement
                + dest.subSequence(dend, dest.length()).toString();
        int input = Integer.parseInt(newVal);
        if (isInRange(min, max, input))
            return null;
    } catch (NumberFormatException nfe) {
    }
    return "";
}

private boolean isInRange(int a, int b, int c) {
    return b > a ? c >= a && c <= b : c >= b && c <= a;
}
}

请帮帮我.. 感谢

3 个答案:

答案 0 :(得分:0)

您可以为TextWatcher分配EditText,然后在那里收听文字更改,例如:

public void afterTextChanged(Editable s) {
   try {
     int val = Integer.parseInt(s.toString());
     if(val > 85) {
        replace(0, length(), "85", 0, 2);
     } else if(val < 18) {
        replace(0, length(), "18", 0, 2);
     }
   } catch (NumberFormatException ex) {
      // Do something
   }
}

答案 1 :(得分:0)

您可以在此editext上使用textwatcher执行您想要的操作,这将是一种实现它的简单方法.Google中的google textwatcher并尝试实现它

答案 2 :(得分:0)

试试这个会帮到你

    YuredittextObject.addTextChangedListener(new TextWatcher(){
        public void afterTextChanged(Editable s) {

         }

        public void beforeTextChanged(CharSequence s, int start, int count, int after){}

        public void onTextChanged(CharSequence s, int start, int before, int count){
            String strEnteredVal = edittext.getText().toString();

            if(!strEnteredVal.equals("")){
            int num=Integer.parseInt(strEnteredVal);
            if(num>18&&num<85){
Toast.maketext(context,"Do not enter the values between 18 to 85",Toast.LENGTH_SHORT).show();
            }else{
             edittext.setText(""+num);             

            }
        }

    });
相关问题