Reputation: 2073
I want to handle the click on the "ok" key of the onscreen keyboard. For that purpose I added a KeyListener to the text field:
textField = (EditText) view.findViewById(R.id.text_field);
textField.setOnKeyListener(new OnKeyListener() {
@Override
public boolean onKey(View view, int keyCode, KeyEvent event) {
boolean handled = false;
if (keyCode == KeyEvent.KEYCODE_ENTER) {
okPressed(view);
handled = true;
}
return handled;
}
});
And in the okPressed method I'm checking the content:
private void okPressed(View view) {
String value = textField.getText().toString().trim();
if (value.equals("")) {
Toast.makeText(view.getContext(), "Error", Toast.LENGTH_SHORT).show();
return;
}
}
And now for the case that my text field is not empty, everything works fine. But in the case the field contains no text, my okPressed method is executed twice. But why?
Upvotes: 2
Views: 550
Reputation: 199880
Each key press is described by a sequence of key events. A key press starts with a key event with ACTION_DOWN.
The last key event is a ACTION_UP for the key up.
You should check the result of getAction() to filter for only the key action you want (i.e., ACTION_UP if you only want to trigger when the user releases or ACTION_DOWN if you want to trigger as soon as they touch the button).
Upvotes: 6