9

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

Java:

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

XML:

android:digits="0123456789"
android:inputType="number"
Josh Correia
  • 3,807
  • 3
  • 33
  • 50
Brinda K
  • 745
  • 3
  • 16
  • 34

7 Answers7

19

Try this:

android:inputType="number|none"
android:maxLength="3"
android:digits="0123456789"
SMR
  • 6,628
  • 2
  • 35
  • 56
1

Set these in your xml of edittext...

android:inputType="numberDecimal"
android:maxLength="3"
Hamid Shatu
  • 9,664
  • 4
  • 30
  • 41
  • 1
    Please read question. It should accept only digits not any other characters like "." or "-" – Brinda K Feb 12 '14 at 10:39
  • I have checked out your conditions. After adding these two attributes the **EditText** field will not take any "." or "-" and it will take only 3 digits, not more than that. – Hamid Shatu Feb 12 '14 at 10:43
  • IMHO this should be the accepted answer. – dazed May 08 '23 at 11:04
0

Set this to your EditText

android:inputType:"number"
android:maxLength:"3"
The Heist
  • 1,444
  • 1
  • 16
  • 32
0

I guess you should do it programmatically with the use of TextWacher class

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)
    {}
});
user3291365
  • 445
  • 3
  • 14
0

Try to put this in your EditText xml declaration :

android:inputType="number|none"

Enjoy coding :)

m4rtin
  • 2,445
  • 22
  • 34
user3775481
  • 109
  • 1
  • 3
  • This answer was already provided by Mr Hamid Shatu as the first comment...So try to be more dynamic. – xxbinxx Sep 04 '14 at 11:45
0

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

android:maxLength="3"

as other users answer you above.

Good luck

Community
  • 1
  • 1
SerSánGal
  • 467
  • 4
  • 15
0

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.

double myValue = 25000;
myInput.setText(String.valueOf(myValue).replace(".0", ""));
Bamz3r
  • 177
  • 2
  • 7