简体   繁体   中英

onKeyDown() in Android not working for virtual keys

I had been searching a lot about this thing, but could not figure it out. So I thought to ask here what exactly the problem I am facing, so that it could help others also (who might face the same problem)

I am having the following code in my Activity

public class MainActivity extends ActionBarActivity implements KeyEvent.Callback{
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        System.out.println("Key down called");
        if ( keyCode == KeyEvent.KEYCODE_MENU ) {
            System.out.println("Menu clicked");
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public boolean onKeyUp(int keyCode, KeyEvent event) {
        System.out.println("On key up");
        if ( keyCode == KeyEvent.KEYCODE_MENU ) {

            System.out.println("up Menu clicked");
            return true;
        }
        return super.onKeyUp(keyCode, event);
    }
}

Where it works (Devices having physical buttons)

If I run the same code in Android device having the physical keys at the bottom then these methods are getting called for Menu button and Back button.

The Problem (Devices having virtual keys)

But if I run the code in a device having the Virtual keys at the bottom (rather than the physical keys) then these methods are NOT being called.

I am able to handle the back press (thanks to onBackPressed() ) but not able to override the Menu button pressed for virtual keys.

Any workaround for this thing? How can I override the menu button in Android devices having Virtual keys.

Thanks.

There is no Menu button in the newer versions, especially which are having virtual buttons at the bottom. It is the Recent Apps button, which has this predefined functionality to show recent applications and it can't be overridden.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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