Search code examples
androidandroid-edittextvirtual-keyboardandroid-inputtype

Allow entering negative sign first for Android EditText of number type


I have multiple EditText with

android:inputType="numberSigned|numberDecimal"

and that works for the most part except when trying to enter negative numbers, I have to enter at least one numeric digit (0~9) first then move cursor to the front to enter the negative sign. I understand that "-" is not a valid "signed decimal number", but forcing the user to move cursor for every field with negative number is counter productive.

Is there a way to make numberSigned allow entering negative sign first, or do I have to implement a custom InputFilter to duplicate most of "numberSigned|numberDecimal" behavior except to allow entering negative sign first?

I have tested this with both Android 8.1 emulator and Android 9 Motorola e6, in case this matters.

EDIT

The title incorrectly assumes "numberSigned" does not allow entering negative sign first by default. It is instead a bug I introduced when I created an InputFilter for these EditText – I accidentally rejected "-" as a valid entry.


Solution

  • Easy solution would be to use the digits keyword.

    <EditText 
      android:id="@+id/editText"
      android:digits="0,1,2,3,4,5,6,7,8,9,-,."
    />
    

    Harder solution would be to implement an InputFilter or a TextWatcher, and make them "override" the inputType behaviour when character is "-" to assess no further work is needed.