Android: Problem with overriding onKeyListener for a Button

佐手、 提交于 2019-12-12 16:25:34

问题


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


回答1:


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


来源:https://stackoverflow.com/questions/3853200/android-problem-with-overriding-onkeylistener-for-a-button

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!