I\'ve attached an OnKeyListener to an EditText. I\'ve overrode the onKey handler to capture a KeyEvent.
When a user hits the enter key (either their computer enter
you can filter like this :
object.setOnKeyListener(new OnKeyListener() {
@Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_ENTER && event.getAction() == KeyEvent.ACTION_UP) {
// do stuff
return true;
}
return false;
}
});
idem when you push the key with KeyEvent.ACTION_DOWN
Ahhhh
I think this is happening for key up and key down?
This event is fired by KeyEvent.ACTION_DOWN
and KeyEvent.ACTION_UP
.
I have done debugging and finally I realize that there is an param called KeyEvent event
that I never use, then I checked and found the problem.
I had the same issue and the answers above helped me but I am using Xamarin.Android (c#) so it is slightly different syntax.. Here is what worked for me:
MyStringTextBox.KeyPressed += OnEnterKeyPressed;
protected void OnEnterKeyPressed(object sender, View.KeyEventArgs e)
{
if (e.KeyCode == Keycode.Enter && e.Event.Action == KeyEventActions.Up)
{
DoSomething(this, EventArgs.Empty);
}
else
{
e.Handled = false;
}
}
This way, the DoSomething() would only be called on hitting Enter Key (Up) only and thus would be fired once. Works and tested on Xamarin.Android
I debugged and what worked for me was that,
editText.setOnKeyListener(View.OnKeyListener { view, i, keyEvent ->
if (i == KeyEvent.KEYCODE_ENTER && enterAsSend && (keyEvent.action == KeyEvent.ACTION_UP || keyEvent.action == KeyEvent.ACTION_DOWN)) {
//Do stuff
}
return@OnKeyListener true
}
false
})
and checkout your Editext that android:inputType="textNoSuggestions"
because the first click of enter key gives us the suggestion from the dictionary.
if (keyCode == KeyEvent.KEYCODE_ENTER && event.getAction()==0) {