How to ensure only legitimate number is entered in EditText

Viewed 486

I have an EditText, that already have inputType is number. This ensure only digit from 0-9 could be entered.

    <androidx.appcompat.widget.AppCompatEditText
        android:id="@+id/uiEditTextNumber"
        android:layout_width="200dp"
        android:layout_height="wrap_content"
        android:layout_marginTop="36dp"
        android:inputType="number"
        android:text="0"
        android:textAlignment="center" />

However, the problem is, user could still enter 000 or even 0123, which doesn't look legitimate. I also want in such a way, when there's no character, it will return to 0 (instead of blank "")

I search on Stackoverflow, and found most question revolve around limiting the enter to using android:inputType="number", but nothing mentioned how to avoid 00 or 0123 by auto convert them to 0 and 123.

I made the function below, but seems hacky, where i have to manually change the text and move the cursor.

        uiEditTextNumber.doAfterTextChanged {
            if (it.isNullOrBlank()) {
                modifyText("0")
                return@doAfterTextChanged
            }
            val originalText = it.toString()
            try {
                val numberText = originalText.toInt().toString()
                if (originalText != numberText) {
                    modifyText(numberText)
                }
            } catch (e: Exception) {
                modifyText("0")
            }
        }

// ... AND the function

    private fun modifyText(numberText: String) {
        uiEditTextNumber.setText(numberText)
        uiEditTextNumber.setSelection(numberText.length)
    }

Any better solution out there?

Note the answer in Is it possible to forbid the first number in a EditText to be "0" is not helping, as it is just preventing the user from entering 01 and 0123, but doesn't automatically change 0 to 1 when one type 1. Besides, it also doesn't ensure when nothing is in the EditText, it automatically set to 0.

1 Answers

to achieve your goal you can add the following function

fun removeLeadingZeros(strNumber: String): String {
        for (i in strNumber.indices) {
            val c = strNumber[i]
            if (c != '0') {
                return strNumber.substring(i)
            }
        }
        //If the number consists only from zeros, return zero.
        return "0"
    }

Then, when you need to get the text from the editText, you can call the function like so

str = removeLeadingZeros(strNumber)
Related