Android - Restrict EditText entry after centain VALUE (ex. $100)

78 Views Asked by At

I would like to restrict the EditText entry with a certain value (not maxlength).

Example - MaxValue is $100.

Possible maximum value inputs are 100, 100.0, 100.00

So I cannot restrict it with maxlength.

Is it possible to restrict when the user enters the value?

or checking the value if(edittextvalue>100) on TextChangeListener is the only option?

2

There are 2 best solutions below

1
On

Is it possible to restrict when the user enters the value?

Yes,You should use TextWatcher . I hope this is best way .

When an object of a type is attached to an Editable, its methods will be called when the text is changed.

private final TextWatcher TxtWatecherExample= new TextWatcher() {
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        public void onTextChanged(CharSequence s, int start, int before, int count) {
         // Add your LOGIC
           if()
           {}
           else
           {}
        }

        }

        public void afterTextChanged(Editable s) {

    };

onTextChanged

void onTextChanged (CharSequence s, int start, int before, int count) This method is called to notify you that, within s, the count characters beginning at start have just replaced old text that had length before. It is an error to attempt to make changes to s from this callback.

0
On

add the addTextChangedListener event to your editText

like this.

        editText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                try {
                    double value = Double.parseDouble(editText.getText().toString());
                    if (value >= 100.0) {
                        // Your code goes here.
                    } else {
                        // Your code goes here.
                    }
                } catch (Exception ex) {
                    // Handle empty string. Since we're passing the edittext value.
                }
            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });

Hope this will help.