当输入的值在

时间:2018-01-02 08:01:39

标签: android

以下是我在编辑文字中使用的代码,仅在某个范围内取值

 EditText.setFilters(new InputFilter[]{ new InputFilterMinMax(Min, Max)});

这是我的功能:

 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) {
        int input = 0;
        try {
            input = Integer.parseInt(dest.toString() + source.toString());
            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;
    }
}

当min为1且max为10时,此代码有效,但当min为20且max为30时,它不起作用 请帮助,提前谢谢

2 个答案:

答案 0 :(得分:0)

这是因为当您开始输入&#39; 20&#39;时,第一个数字是2,而2不是20到30之间。

我建议你改用TextWatcher:

TextWatcher textWatcher = new TextWatcher() {

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

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {

        if(s.length() > 0) {
            int num = Integer.parseInt(s);
            if (num >= Min && num <= Max)
            {
                // Place your logic here. EG : save the number.
            }
            else{
                // Your are not in the desired range. 
            }
        }
    }

    @Override
    public void afterTextChanged(Editable s) {

    }
};

EditText.addTextChangedListener(textWatcher);

答案 1 :(得分:0)

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) {
        int input = 0;
        try {
            **if(end==1){
               min = Integer.parseInt(source.toString());
            }**
            input = Integer.parseInt(dest.toString() + source.toString());
            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;
    }
}

追加if (end==1) { min = Integer.parseInt(source.toString()); }对我来说很好。

但是,对于您尝试实施的内容,更好的方法是使用Thomas

中提到的TextWatcher