Is it possible to prohibit the first number in EditText to be "0",

Hi, I just want to know if it is possible to prohibit the first number that the user can enter, "0".

<EditText
        android:id="@+id/editText1"
        android:layout_width="50dp"
        android:layout_height="35dp"  
        android:layout_marginBottom="2dp" 
        android:maxLength="2"
        android:inputType="number"
        android:digits="123456789">
        <requestFocus />
    </EditText>

Using this code, however, does not allow the user to enter “0” at all, but I want only the first digit to be “0”

+4
source share
3 answers

if you want the user to not enter 0 only at the beginning, try the following:

editText1.addTextChangedListener(new TextWatcher(){
        public void onTextChanged(CharSequence s, int start, int before, int count)
        {
            if (editText1.getText().toString().matches("^0") )
            {
                // Not allowed
                Toast.makeText(context, "not allowed", Toast.LENGTH_LONG).show();
                editText1.setText("");
            }
        }
        @Override
        public void afterTextChanged(Editable arg0) { }
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
    }); 
+8
source

For this purpose in Java, you can extend the class InputFilterand set a minimum value 10for your EditText:

package your.package.name

import android.text.InputFilter;
import android.text.Spanned;

public class InputFilterMin implements InputFilter {

    private int min;

    public InputFilterMin(int min) {
        this.min = min;
    }

    @Override
    public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {   
        try {
            int input = Integer.parseInt(dest.toString() + source.toString());
            if (input >= min)
                return null;
        } catch (NumberFormatException nfe) { }     
        return "";
    }
}

Then use this class in your activity:

EditText et = (EditText) findViewById(R.id.editText1);
et.setFilters(new InputFilter[]{ new InputFilterMin(10)});

, 10.

0

...

editText.addTextChangedListener(new TextWatcher() {

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

          long data=Long.parseLong(editText.toString());
          editText.setText(""+data);
        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count,
                int after) {

        }

        @Override
        public void afterTextChanged(Editable arg0) {

        }
    });
0

Source: https://habr.com/ru/post/1545977/


All Articles