Search code examples
androidif-statementkeyevent

Why is both sides of the if else statement being executed, and how to fix it?


I have a block of code:

passwordEditText.setOnKeyListener(new OnKeyListener() 
    {
        @Override
        public boolean onKey(View v, int keyCode, KeyEvent event) 
        {
            if (keyCode == KeyEvent.KEYCODE_ENTER)
            {
                launch.performClick();
                return true;

            }
            else
            {
                return false;
            }
        }
    });

What I want is that when the enter key is pressed it performs the log in command (launch is the button that executes the log in). However, after executing the true block, it continues on to execute the else block as well, returning false and causing (only on some devices) the log in to occur a second time.

So my question is in two parts: How can a if else statement evaluate as both true and false, and how can I make it so it doesn't do that. I have thought of a couple of tricks to make that happen but this seems to be a problem that is better understood then quickly patched.


Solution

  • What you are seeing is the OnKey is fired twice, the first time for key down, and the second time for key up, so you have to filter it with

        if (event.getAction()!=KeyEvent.ACTION_DOWN) {
            return true;
        }
    
        switch (keyCode) {
           case KeyEvent.KEYCODE_1 : 
                //do something
                break;
           case KeyEvent.KEYCODE_2 : 
                //do something
                break;
           case KeyEvent.KEYCODE_3 : 
                //do something
                break;
        }
    
        return true;