How to programmatically set EditText's InputType to integer or decimal?

user7085962 picture user7085962 · Nov 7, 2016 · Viewed 27.7k times · Source

How do I programmatically configure an EditText to allow:

  1. Positive or negative integer values

  2. Positive or negative decimal values

I am having a hard time finding what gets this working even with https://developer.android.com/reference/android/text/InputType.html

Answer

Anuja Kothekar picture Anuja Kothekar · Nov 7, 2016

You can use this code:

EditText edt = new EditText(context);
edt.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL); //for decimal numbers
edt.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_SIGNED); //for positive or negative values

If together:

edt.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL | InputType.TYPE_NUMBER_FLAG_SIGNED);