Reputation: 1338
I have two EditText fields, one for username and one for password. When I finish typing the username and press enter, I want focus to switch to the password. When I finish password and press return, some code is also run.
My problem is that when I finish typing the code for the username and press return, both segments of code are run. Below is my code:
userNameEditText.setOnKeyListener(new View.OnKeyListener() {
@Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_ENTER && userNameEditText.hasFocus()) {
passwordEditText.requestFocus();
return true;
}
return false;
}
});
passwordEditText.setOnKeyListener(new View.OnKeyListener() {
@Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_ENTER && passwordEditText.hasFocus()) {
attemptLogin(userNameEditText, passwordEditText);
InputMethodManager inputManager = (InputMethodManager) activity.getSystemService(activity.INPUT_METHOD_SERVICE);
inputManager.hideSoftInputFromWindow(passwordEditText.getWindowToken(), 0);
return true;
}
return false;
}
});
What should I do so that only the code for the selected EditText is run when I press enter on the keyboard?
Upvotes: 0
Views: 33
Reputation: 326
Your problem is that you haven't tested for the type of KeyEvent.
The first listener is being fired when event.getAction()==ACTION_DOWN and then the second is being fired when event.getAction()==ACTION_UP.
You need to change your listener to check for the type of action as well as key, I would recommend only firing your action on ACTION_UP.
Upvotes: 2