views:

36

answers:

1

Hi,

I want a certain functionality when Enter key is pressed on a Button. When I override onKey(), I write the code to be executed for KEY_ENTER. This works fine.

setupButton.setOnKeyListener(new OnKeyListener() {
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if (KeyEvent.KEYCODE_ENTER == keyCode)
                {
                    Intent setupIntent = new Intent(getApplicationContext(),SetUp.class);
                    startActivityForResult(setupIntent, RESULT_OK);
                }
                return true;
            }
        });

But no other keys work for the Button now like the Up, Down arrow keys etc. I know this is because I have overriden the onKey() for only ENTER.

But is there a way I can retain the functionality for all other keys and override only for some specific keys?

Note: All this is because my onClick() is not called when Enter key is pressed. Hence, I need to override onKey() itself.

- Kiki

+3  A: 

When you return true in the function, that tells Android you are handling all keys, not just the Enter key.

You should return true only at the end, inside the if statement and return false at the end of the function.

setupButton.setOnKeyListener(new OnKeyListener() {
        public boolean onKey(View v, int keyCode, KeyEvent event) {
            if (KeyEvent.KEYCODE_ENTER == keyCode)
            {
                Intent setupIntent = new Intent(getApplicationContext(),SetUp.class);
                startActivityForResult(setupIntent, RESULT_OK);
                return true;
            }
            return false;
        }
    });
Matthieu
Hey, thanks a lot Matthieu. I'd no idea till you told me!
kiki