0

I have an edittext in my activity and users can type only letters. I want to check if user types something else not letter. How can i do that?

I've tried using onKeyListener but i think that's the wrong way to do that because you have to write so much "else if" blocks for every other keys which are not letters.

<EditText
           android:id="@+id/editText"
           android:layout_width="match_parent"
           android:layout_height="wrap_content"
           android:background="@android:color/transparent"
           android:inputType="textMultiLine"
           android:digits="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz">
</EditText>

For example, when user clicks space i want to show him an alert dialog that says "you can type only letters!". or clicks numbers or clicks slash.

Onur
  • 25
  • 1
  • 8
  • 2
    Set an `InputFilter` on `EditText`..[See this](https://stackoverflow.com/questions/3349121/how-do-i-use-inputfilter-to-limit-characters-in-an-edittext-in-android) – ADM Apr 20 '19 at 15:11
  • @ADM that is exactly what i want. Thank you sir. – Onur Apr 20 '19 at 16:05

1 Answers1

0

Try this:

 editText.setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                String src = (char)event.getUnicodeChar()+"";
                if(src.toString().matches("[a-zA-Z ]+")&&!src.equals(" ")||keyCode==KeyEvent.KEYCODE_DEL){
                    // do something here
                }
                else {
                    // alert dialog that says "you can type only letters!".
                }
                return false;
            }
        });
  • I solved it with inputFilter just like @ADM said. But your solution looks well too. – Onur Apr 20 '19 at 20:17