Enter key on EditText hitting onKey twice

前端 未结 7 1868
暖寄归人
暖寄归人 2021-01-07 18:25

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

相关标签:
7条回答
  • 2021-01-07 19:16

    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

    0 讨论(0)
  • 2021-01-07 19:19

    Ahhhh

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

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2021-01-07 19:24

    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

    0 讨论(0)
  • 2021-01-07 19:27

    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.

    0 讨论(0)
  • 2021-01-07 19:29
    if (keyCode == KeyEvent.KEYCODE_ENTER && event.getAction()==0) {
    
    0 讨论(0)
提交回复
热议问题