Question

I am creating login screen with 2 editTexts: etUsername and etPassword.

On the etUsername, user should input the username and press Enter to go to the edit text etPassword, then he inputs the password, press Enter to login. Here is my current code:

  etUsername.setOnKeyListener(new OnKeyListener() {   
   @Override
   public boolean onKey(View v, int keyCode, KeyEvent event) {
    if ((keyCode == KeyEvent.KEYCODE_ENTER)) {         
     etPassword.requestFocus();
     return true;
    } else
     return false;
   }
  });

  etPassword.setOnKeyListener(new OnKeyListener() {   
   @Override
   public boolean onKey(View v, int keyCode, KeyEvent event) {
    if ((keyCode == KeyEvent.KEYCODE_ENTER)) {         
     loginToServer();
     return true;
    } else
     return false;
   }
  });

But when I input the username, and then press Enter – the program tries to log in to the server.

In the debug mode, I saw that when I pressed Enter once (on the etUsername) then first: etUsername.onKey() is called and then etPassword.onKey() is also called !

How can I modify the code so that the ENTER event is only processed once for the current field?

Was it helpful?

Solution

Before you check which key is pressed, try adding a check for which key event occurs. I would guess that it first triggers on the key-down event, then you move focus to the second text field, and here it also triggers on the key-up event.

See here for an example on how to check both the event type and key: Use "ENTER" key on softkeyboard instead of clicking button

I'm not 100% sure of this, but it is worth a try :-)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top