How To Validate an EditText to handle numbers only in Android?

醉酒当歌 提交于 2021-02-07 08:18:27

问题


How can I validate a text view in android to handle positive integer numbers?

I don't want it to accept any character or signs etc...


回答1:


Have you taken a look at the EditText's inputType attribute? You can set a whole bunch of different input types that the EditText should limit the user input to.

From the sounds of it, you're probably looking for something like:

<EditText
    ....
    android:inputType="number" 
     ... />



回答2:


You can use regular expressions. See: http://developer.android.com/reference/java/util/regex/Pattern.html

Your pattern could look like ^[0-9]{1,10}$ which means that the entered value can only consist of digits (minimum 1, maximum 10)




回答3:


IMO best way is use inputType in xml

<EditText
    ...
    android:inputType="phone" />

You have to remember that "+" is also part of the phone number.




回答4:


Use the code in your Edittext XML to restrict any range of values

android:digits="0123456789"



回答5:


You can use from XML

<EditText
    ...
    android:inputType="phone" />

or programmatically

EditText editText = (EditText) findViewById(R.id.yourId);
editText.setInputType(InputType.TYPE_CLASS_NUMBER);


来源:https://stackoverflow.com/questions/9449513/how-to-validate-an-edittext-to-handle-numbers-only-in-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!