简体   繁体   English

有没有办法为 EditText 定义最小值和最大值。 EG 20 - 200(不是从 1 开始)

[英]Is there a way to define a min and max value for a EditText. EG 20 - 200 (not starting at 1)

I keep seeing this example everywhere I look to find a way to define the min and max of a EditText .我到处都能看到这个例子,我希望找到一种方法来定义EditText的最小值和最大值。 I kind of understand what it does but I found that it breaks if the min is bigger then 10. Is there any way this code could be changed so that the min can be any number?我有点理解它的作用,但我发现如果最小值大于 10,它就会中断。有什么方法可以更改此代码,以便最小值可以是任何数字吗? And is there any easier way of doing this as it seems to be over-complicated for a simple task?有没有更简单的方法来执行此操作,因为它对于一项简单的任务来说似乎过于复杂了?

 ClassName.setFilters(new InputFilter[]{ new InputFilterMinMax("1", "200")});
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 {
            int 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;
    }

there will be some event, Here I'm taking button click event会有一些事件,这里我正在处理按钮点击事件

@Override
public void onClick(View view) {

String guessSize=editText.getText().toString();
if(Integer.parseInt(guessSize)<=20 || Integer.parseInt(guessSize)>=200)
{
    //Anything you want
    Toast.makeText(MainActivity.this, "No wroking", Toast.LENGTH_SHORT).show();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM