androidandroid-edittextandroid-inputtype

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


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


Solution

  • 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);