android: the first digit in the edit text can not be zero

Dariush Malek picture Dariush Malek · Jul 5, 2013 · Viewed 12.2k times · Source

I have an EditText element with a number input type. I don't want users to be able to enter 0 as the first digit. Can I enforce this using XML?

Here is what I have currently:

<EditText 
                android:id="@+id/main_edt_loan"
                android:layout_width="fill_parent"
                android:layout_height="40dip"
                android:background="@drawable/sample_editbox"
                android:ems="10"
                android:layout_margin="10dip"
                android:inputType="number"
                android:hint=""
                android:ellipsize="start" 
                android:maxLines="1"
                android:imeOptions="actionNext"
                android:textSize="18dip"
                android:gravity="center"
                android:digits="0123456789"
                android:maxLength="10"
                android:textColor="#000000"/>

Answer

Prashant Jajal picture Prashant Jajal · Jul 26, 2018

Its just simple as that.

edContactNumber.addTextChangedListener(new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

        }

        @Override
        public void afterTextChanged(Editable s) {
            if (s.toString().length() == 1 && s.toString().startsWith("0")) {
                s.clear();
            }
        }
    });