Home > Software design >  Android Studio: only accept input if its a letter using TextChangedListener
Android Studio: only accept input if its a letter using TextChangedListener

Time:04-20

I'm working on an app using Android Studio where I want to take input from the user and use it later on.

I want to only accept this input if its a letter. If the user inputs a number I want to show the user an error message instead of accepting the input.

This is the code I'm currently working on, at the moment it accepts whatever input the user enters:

EditText input;

input.setText("");

input = findViewById(R.id.input);

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

                    if (charSequence.length() != 0) {
                        useInputLaterOn(charSequence.charAt(0));
                    }
                }

                @Override
                public void afterTextChanged(Editable editable) {
                }

            });

CodePudding user response:

Use this code to check for a letter and show error if it's not a letter

input.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) {
                if (charSequence.length() == 0) return;// No need to check because there's no text
                Pattern pattern = Pattern.compile("^[a-zA-Z ] $");
                Matcher matcher = pattern.matcher(charSequence.toString());
                if (!matcher.matches()) {
                    // It's not a letter
                    // Remove last entered character and show error message
                    input.setText(charSequence.toString().substring(0, charSequence.toString().length() - 1));
                    input.setSelection(input.getText().toString().length());
                    input.setError("Not a letter");
                } else {
                    // It's a letter do something
                }
            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });
  • Related