开发者

Android: onKeyListener simulating two instances of a pressed key [duplicate]

开发者 https://www.devze.com 2023-02-11 20:12 出处:网络
This question already has answers here: Closed 10 years ago. Possible Duplicate: public boolean onKey() called twice?
This question already has answers here: Closed 10 years ago.

Possible Duplicate:

public boolean onKey() called twice?

Display.setOnKeyListener(new OnKeyListener() {
    public boolean onKey(View v, int keyCode, KeyEvent event) {
        switch (keyCode) {
             case KeyEvent.KEYCODE_ENTER:
                solveExpression();
      开发者_StackOverflow社区          return true;
        }
        return false;
    }
});

I'm trying to solve the expression contained within the Display(EditText), by pressing the enter button on the keyboard, yet it always interprets it as though I pressed the button twice. Does anyone know why this happens?


Try...

Display.setOnKeyListener(new OnKeyListener() {    
    public boolean onKey(View v, int keyCode, KeyEvent event) {
        switch (keyCode) {
            case KeyEvent.KEYCODE_ENTER:

                // Check for ACTION_DOWN only...
                if (KeyEvent.ACTION_DOWN == event.getAction()) {
                    solveExpression();
                    return true;
                }
        }
    }
});

The 'action' can be ACTION_DOWN, ACTION_UP or ACTION_MULTIPLE (the last being for when a key is pressed and held). onKey() will be called for any/all of those actions.

As the other answer mentions, it's triggering twice because it's once for down and once for up.


if (event.getAction()!=KeyEvent.ACTION_DOWN) // we catch only key down events
    return true;

Thus you stop listening other keyevents as onClick.

If you want nobody else further in chain to get the event for another piece of work, you should set

    return false; 


not an android guy either but the fact that it registers twice makes me think that OnKey encompasses a onKeyDown and onKeyUp. Would listening to onKeyUp work for you as well?

0

精彩评论

暂无评论...
验证码 换一张
取 消