7

Hi I just want to know if it is possible to forbid the first number that the user can enter to be "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 prevents the user from entering "0" at all but I want just the first digit not to be "0"

user3182266
  • 1,270
  • 4
  • 23
  • 49

3 Answers3

14

if you want to avoid the user from entering 0 only at the beginning, then try this:

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) {}
    }); 
Badrul
  • 1,582
  • 4
  • 16
  • 27
2

For this purpose in Java, you could extend InputFilter class and set a minimum value of 10 for 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)});

now users are allowed to enter values equal or greater than 10.

0

You can try this...

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) {

        }
    });
Sathish
  • 33
  • 4