Enter key on EditText hitting onKey twice

2020-03-09 07:03发布

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 key while using the emulator, or the hardware enter key on their phone with a hardware keyboard), the onKey handler gets executed twice. Both executions have the keyCode 66.

Why is this happening?

I want my screen so when the user hits the enter key, a search is performed. Because of what is happening, the search is needlessly happening twice.

My method looks like this:

   mFilter.setOnKeyListener(new View.OnKeyListener() {

        public boolean onKey(View v, int keyCode, KeyEvent event) {
            if (keyCode == KeyEvent.KEYCODE_ENTER) {
                // perform search
                return true;
            }
            return false;
        }
    });

标签: android
7条回答
Juvenile、少年°
2楼-- · 2020-03-09 07:34

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.

查看更多
趁早两清
3楼-- · 2020-03-09 07:35

Ahhhh

I think this is happening for key up and key down?

查看更多
beautiful°
4楼-- · 2020-03-09 07:35

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
5楼-- · 2020-03-09 07:37

Try this:

mFilter.setOnKeyListener(new View.OnKeyListener() {
    public boolean onKey(View v, int keyCode, KeyEvent event) {
        if (event.getAction() == KeyEvent.ACTION_DOWN) {
            if (keyCode == KeyEvent.KEYCODE_ENTER) {
                // perform search
                return true;
            }
        }
        return false;
    }
});
查看更多
\"骚年 ilove
6楼-- · 2020-03-09 07:44

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

查看更多
啃猪蹄的小仙女
7楼-- · 2020-03-09 07:47
if (keyCode == KeyEvent.KEYCODE_ENTER && event.getAction()==0) {
查看更多
登录 后发表回答