Android EditText将输入限制为数字范围

时间:2019-06-21 12:09:16

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

我试图将数字编辑文本仅限制为一个数字范围。我已经找到了一些使用InputFilter做到这一点的教程,但是一旦实现,我将无法再输入EditText。

根据教程,我创建一个类为:

package africa.mykagovehicles;

import android.text.InputFilter;
import android.text.Spanned;

public class InputFilterMinMax implements InputFilter {
    private int minimumValue;
    private int maximumValue;

    public InputFilterMinMax(int minimumValue, int maximumValue) {
        this.minimumValue = minimumValue;
        this.maximumValue = maximumValue;
    }

    @Override
    public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
        try {
            int input = Integer.parseInt(dest.subSequence(0, dstart).toString() + source + dest.subSequence(dend, dest.length()));
            if (isInRange(minimumValue, maximumValue, 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;
    }
}

然后在活动中,我将InputFilter设置为:

txtYearOfManufacture.setFilters(new InputFilter[] {new InputFilterMinMax(1950, 2020)});

不知道为什么我不能输入EditText。任何帮助表示赞赏。

1 个答案:

答案 0 :(得分:-1)

尝试如下更改代码

import android.text.InputFilter;
import android.text.Spanned;


public class InputFilterMinMax implements InputFilter {
    private int minimumValue;
    private int maximumValue;

    public InputFilterMinMax(int minimumValue, int maximumValue) {
        this.minimumValue = minimumValue;
        this.maximumValue = maximumValue;
    }
    public InputFilterMinMax(String minimumValue,String maximumValue) {
        this.minimumValue = Integer.parseInt(minimumValue);
        this.maximumValue = Integer.parseInt(maximumValue);
    }

    @Override
    public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
        try {
            int input = Integer.parseInt(dest.subSequence(0, dstart).toString() + source + dest.subSequence(dend, dest.length()));
            if (isInRange(minimumValue, maximumValue, 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;
    }
}