Search code examples
androidandroid-edittextfeedback

Give user feedback on EditTexts with limited InputType


I have an EditText with a restricted InputType, like this: latEdit.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL);

This only accepts float/double values.

So when a user tries to type characters that are not allowed, nothing happens.
I would like to give the user feedback when that happens. E.g. "only decimals allowed" in a toast.


My guess would have been to use onTextChanged and try to validate the input there, but I'm not sure that method would even be called with restricted input.


EDIT
I used the idea of M.Saad Lakhan's answer, removed the setInputType flags and solved it with this regex and the setError method:

public void onTextChanged(CharSequence s, int start, int before, int count) {
        if (!s.toString().matches("[0-9]{1,13}(\\.[0-9]*)?"))
        {
            latEdit.setError(wrongInputWarning);
        }
    }

Solution

  • You dont need to do that:

    latEdit.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL);
    

    You need to addTextChangeListener on your edit text as follows:

    yourEditText.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) {
           if (!s.matches("(?<=^| )\d+(\.\d+)?(?=$| )"))
                {
                    Toast.makeText(getApplicationContext(), "Only digits and . are allowed", Toast.LENGTH_LONG).show();
                    etNewPassword.requestFocus();
                    return;
                }
        }
    
        @Override
        public void afterTextChanged(Editable s) {
            textv.setText(s);
        }
    });
    

    In on text changed you have to apply checks according to your requirements