开发者

Android: Problem with overriding onKeyListener for a Button

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


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;
        }
    });
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜