简体   繁体   English

Android:覆盖按钮的onKeyListener问题

[英]Android: Problem with overriding onKeyListener for a Button

I want a certain functionality when Enter key is pressed on a Button. 当按下按钮上的Enter键时,我想要一个特定的功能。 When I override onKey(), I write the code to be executed for KEY_ENTER. 当我重写onKey()时,我编写了要为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. 但现在没有其他按键可用于按钮,例如向上,向下箭头键等。我知道这是因为我已经覆盖仅用于输入的onKey()。

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. 注意:所有这一切都是因为按下Enter键时未调用onClick()。 Hence, I need to override onKey() itself. 因此,我需要覆盖onKey()本身。

- Kiki - 琪琪

When you return true in the function, that tells Android you are handling all keys, not just the Enter key. 当您在函数中返回true时,告诉Android您正在处理所有键,而不仅仅是Enter键。

You should return true only at the end, inside the if statement and return false at the end of the function. 您应该仅在结尾处,在if语句内返回true,并在函数末尾返回false。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM