javaandroidandroid-edittextkeylistener

How to know if user is typing something in an Edittext (Android)


So the idea is to check if the user is typing anything and then take that text length and show it somewhere. I used the max length attribute to limit the user entering big text, but I also want it to be showed for the user. This picture will make things clear- Edittext

I don't know how to listen for key pressed. I just want to take the text every time user types one character even space or backspace, I want to take the text, get the length of it and show it below. Is there any way to that? What's the way to listen for key pressing in Java?

I tried to use setOnKeyListener, but it didn't work, or I couldn't understand how it works. How to do this specific part programatically? The code I wrote, though I know it's wrong-

binding.about.setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View view, int i, KeyEvent keyEvent) {
                if(keyEvent.getAction() == KeyEvent.ACTION_DOWN)
                    Toast.makeText(ProfileActivity.this, "Key Pressed", Toast.LENGTH_SHORT).show();
                return true;
            }
        });

Solution

  • Your can use the following snippet

    binding.edittext.addTextChangedListener(new TextWatcher() {
    
       public void afterTextChanged(Editable s) {}
    
       public void beforeTextChanged(CharSequence s, int start,
         int count, int after) {
       }
    
       public void onTextChanged(CharSequence s, int start,
         int before, int count) {
          // when text is changed in edittext
       }
    });