java Android 将 EditText 限制为仅整数输入

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10467025/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 01:10:29  来源:igfitidea点击:

Android Limit EditText to Integer input only

javaandroid

提问by Somk

I am trying to apply some kind of verification to an edittext. A user should only be able to enter integers between 1 and 60. I am wondering whether I should let them type whatever they like and when they focus off of the edittext check the contents and if it is out of bounds change the value to a default, say 0.

我正在尝试对编辑文本应用某种验证。用户应该只能输入 1 到 60 之间的整数。我想知道我是否应该让他们输入他们喜欢的任何内容,当他们关注编辑文本时检查内容,如果超出范围将值更改为默认值,说 0。

Or is there a way to limit the keyboard to only allow integers?

或者有没有办法限制键盘只允许整数?

UPDATE: I am doing everything programmatically. So far I have been able to limit to only numeric input and have a maximum of 2 characters by implementing the following. I am still struggling to limit only values between 0 and 60 though.

更新:我正在以编程方式做所有事情。到目前为止,通过实现以下内容,我已经能够限制为仅数字输入并最多输入 2 个字符。不过,我仍在努力将值限制在 0 到 60 之间。

    editText.setInputType( InputType.TYPE_CLASS_NUMBER );
    InputFilter[] FilterArray = new InputFilter[1];
    FilterArray[0] = new InputFilter.LengthFilter(2);
    editText.setFilters(FilterArray);

回答by Arun Chettoor

You can make use of android.text.method.KeyListenerto replace the current input with whatever you like.

您可以使用android.text.method.KeyListener用您喜欢的任何内容替换当前输入。

Since you dont have to change all the keys you can use addTextChangedListener(TextWatcher watcher)method like this:

由于您不必更改所有键,您可以使用这样的addTextChangedListener(TextWatcher watcher)方法:

EditText editT = (EditText) findViewById(R.id.your_id);
editT.addTextChangedListener(new TextWatcher() {
@Override
public void afterTextChanged(Editable s) {
    // TODO Auto-generated method stub
}

@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
    // TODO Auto-generated method stub
}

@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
    // TODO Auto-generated method stub

});

Make use of it to check whether your input is beyond what you are looking and you can even neglect the keys by checking on that loop.

利用它来检查您的输入是否超出了您的预期,您甚至可以通过检查该循环来忽略键。

In XML:

在 XML 中:

  • If you are using numbers only use android:inputType="number".
  • To limit the no of digits to 2 include android:maxLength="2".
  • 如果您使用数字,请仅使用android:inputType="number".
  • 要将位数限制为 2,包括android:maxLength="2".

回答by Jamie E

I've got it! I scoured the internet forever, and put a few things together to get it to work. Basically what it does is runs a parallel process that will be constantly running while the user has their focus on the particular edittext box. It will set a filter so that the user can only enter 0-5 in the first integer slot, but will be allowed to enter 0-9 for the second. This will obviously give 0-59 instead of 1-60, but that's what you want for seconds anyways. This code goes before the onCreate method, inside of your class:

我懂了!我永远在互联网上搜索,并把一些东西放在一起让它工作。基本上它所做的是运行一个并行进程,当用户将注意力集中在特定的编辑文本框上时,该进程将不断运行。它将设置一个过滤器,以便用户只能在第一个整数槽中输入 0-5,但允许在第二个整数槽中输入 0-9。这显然会给出 0-59 而不是 1-60,但这无论如何都是你想要的。此代码在您的类中的 onCreate 方法之前:

final InputFilter filter = new InputFilter() 
{
    public CharSequence filter(CharSequence source, int start, int end,
                Spanned dest, int dstart, int dent)
    {
        for (int i = start; i < end; i++)
        {
            if ((source.charAt(start) == "6".charAt(0)) || (source.charAt(start) == "7".charAt(0)) || (source.charAt(start) == "8".charAt(0))
                    || (source.charAt(start) == "9".charAt(0)) || (!Character.isDefined(source.charAt(i))) )                            
            {
                return "";
            }
        }
        return null;
    }
 };

private class FilterCheckerTask extends AsyncTask<Void, Void, Void>
{       
    @Override
    protected Void doInBackground(Void... params) 
    {           
        while(true)
        {               
            if (<EditText>.getText().toString().isEmpty())
            {
                Log.e("empty","empty");                 
                <EditText>.setFilters(new InputFilter[]{filter, new InputFilter.LengthFilter(2)});              
            }
            else if (<EditText>.getText().toString().charAt(0) >= "6".charAt(0))
            {
                Log.e("front num bad","greater than 5");
                <EditText>.setFilters(new InputFilter[]{filter, new InputFilter.LengthFilter(2)});
            }
            else 
            {
                Log.e("unfiltered", "unfiltered");
                <EditText>.setFilters(new InputFilter[]{new InputFilter.LengthFilter(2)});      
            }
            if (kicker)
            {
                return null;
            }
        }           
    }       
}

Then, within the onCreatemethod:

然后,在onCreate方法中:

    Time_sec.setOnFocusChangeListener(new OnFocusChangeListener() 
    {
        public void onFocusChange(View v, boolean hasFocus)
        {
            new FilterCheckerTask().execute();
            if(!hasFocus)
                    {kicker = !hasFocus;}                               

        }
    });

As I said in the first part, this will make it so the user can only input numbers between 00 and 59 in your edittext box. I know it may look a little sloppy, and it can probably be cleaned up a bit in some of the if statements, but as far as I can tell it works absolutely perfectly, and doesn't seem to slow the system at all. Hope this helps you, and if not, the future googlers.

正如我在第一部分所说的那样,这将使用户只能在您的编辑文本框中输入 00 到 59 之间的数字。我知道它可能看起来有点草率,并且可以在某些 if 语句中稍微清理一下,但据我所知,它绝对完美地工作,并且似乎根本不会减慢系统的速度。希望这对你有帮助,如果没有,对未来的谷歌员工也有帮助。

回答by La bla bla

If you limit to numbers only, you could use the

如果您仅限于数字,则可以使用

EditText.addTextChangedListener

to get the value inputed and verify it's not over 60

获取输入的值并验证它不超过 60

You can easily allow only numbers by adding android:numeric="integer"to the EditTextin the layout xml file

您可以通过添加android:numeric="integer"EditText布局 xml 文件中轻松只允许数字

Though it is worth mentioning that android:numeric="integer"is now deprecated

虽然值得一提的android:numeric="integer"是现在已弃用