How to only allow positive numbers in an EditText

Getek99 picture Getek99 · Oct 24, 2014 · Viewed 13.1k times · Source

I have a TextWatcher that enables a button when all the EditTexts length() are != 0. I now want to add the ability to also make sure the number is positive. I tried putting a new if() inside the other if() to check if >0 but for some reason it doesn't work.

So what I need is to make sure all EditText are not empty and positive numbers have been entered then enable the number.

This is what I have,

    public TextWatcher localWatcher = 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) {
    }

    // When the text is edited, I want to check if all textViews are filled
    @Override
    public void afterTextChanged(Editable s) {

        // Check if any of the TextViews are == 0, if so the button remains disabled
        if      (et1local.getText().toString().length() == 0
                || et2local.getText().toString().length() == 0
                || et3local.getText().toString().length() == 0
                || et4local.getText().toString().length() == 0
                || et5local.getText().toString().length() == 0
                || et6local.getText().toString().length() == 0
                || et7local.getText().toString().length() == 0
                || et8local.getText().toString().length() == 0
                || et9local.getText().toString().length() == 0) {

            if(et1local){




        localCalculateButton.setEnabled(false);
            }

        }

        // When all are filled enable the button
        else {
            localCalculateButton.setEnabled(true);
        }
    }
};

This works fine but how to also check if the number is positive, any help wpuld be great thanks.

Answer

Vito picture Vito · Oct 24, 2014

You should use the attr of EditText:

android:digits="0123456789."
android:inputType="number"

http://developer.android.com/reference/android/widget/TextView.html#attr_android:digits

So user will be able enter only digits without minus.

UPDATED: Something like that, to prevent first sign from 0:

    editText.addTextChangedListener(new TextWatcher() {
        @Override
        public void afterTextChanged(Editable edt) {
            if (edt.length() == 1 && edt.toString().equals("0"))
                editText.setText("");
        }

        // ...
    });