Java 编辑文本在android中只接受数字而不是十进制数字

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21725115/
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-08-13 10:20:18  来源:igfitidea点击:

edit text accept only numbers not decimal numbers in android

javaandroidregex

提问by Brinda K

My Edit text should accept only 3 digit number, not any other decimal numbers. I used below regular expression to do that but this is even accepting characters like "." and "-". So how to avoid accepting decimal values?

我的编辑文本应该只接受 3 位数字,而不是任何其他十进制数字。我使用下面的正则表达式来做到这一点,但这甚至接受像“。”这样的字符。和 ”-”。那么如何避免接受十进制值呢?

        pattern=Pattern.compile("[0-9]{0,2}");

even i set the edit text to

即使我将编辑文本设置为

        android:digits="0123456789"
        android:inputType="number"  

This is not working. How to solve?

这是行不通的。怎么解决?

采纳答案by SMR

Try this:

尝试这个:

android:inputType="number|none"
android:maxLength="3"
android:digits="0123456789"

回答by The Heist

Set this to your EditText

将此设置为您的 EditText

android:inputType:"number"
android:maxLength:"3"

回答by user3291365

I guess you should do it programmatically with the use of TextWacherclass

我想您应该使用TextWacher类以编程方式进行

editText.addTextChangedListener(new TextWatcher()
{
    Handler handler = new Handler();
    Runnable delayedAction = null;

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

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

    @Override
    public void afterTextChanged( final Editable s)
    {}
});

回答by Hamid Shatu

Set these in your xml of edittext...

在您的edittext xml中设置这些...

android:inputType="numberDecimal"
android:maxLength="3"

回答by user3775481

Try to put this in your EditText xml declaration :

尝试将其放入您的 EditText xml 声明中:

android:inputType="number|none"

Enjoy coding :)

享受编码:)

回答by SerSánGal

You can use this answerto solve your problem. Also to limited the number of digits you can use:

您可以使用此答案来解决您的问题。还要限制您可以使用的位数:

android:maxLength="3"

as other users answer you above.

正如其他用户在上面回答你的那样。

Good luck

祝你好运

回答by Bamz3r

Event if the input is not accept decimal. In my case if i set text to input programmatically, the result will be decimal (added .0 at the end). So, to solve that i replace it when i set the text.

输入不接受十进制时的事件。在我的情况下,如果我将文本设置为以编程方式输入,结果将是十进制(最后添加 .0)。所以,为了解决这个问题,我在设置文本时替换它。

double myValue = 25000;
myInput.setText(String.valueOf(myValue).replace(".0", ""));