0

我有一个编辑文本,我想将插入该编辑文本中的数值限制在 18 到 85 之间。我目前在我的编辑文本上使用这个 InputFilter。但对我没用

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;
}
}

请帮帮我..谢谢

4

3 回答 3

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);             

            }
        }

    });
于 2014-07-09T10:40:34.717 回答
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
   }
}
于 2014-07-09T10:27:10.173 回答
0

您可以在此编辑文本上使用 textwatcher 来做您想做的事情,这将是实现它的一种简单方法。Android 中的 Google textwatcher 并尝试实现它

于 2014-07-09T10:28:50.033 回答