How to access menu button onLongClick in Android?

做~自己de王妃 提交于 2020-01-04 02:04:07

问题


How can I set a listener for long-click performed on hardware Menu button? What is the way of programmatic access to the Menu button?

Moreover how can I distinguish long-click from single-click? (As far as I know when long-click is performed the single-click event is propagated as well - I do not want this to happen because I need 2 different actions for these 2 situations. Long-click and single-click separate listeners for the device Menu button)

Thank you!


回答1:


This shoule be fairly straight forward. Check out the KeyEvent.Callback on the Android developer's website.

There you will find onKeyLongPress() as well as onKeyDown() and onKeyUp(). This should get you on the right track. Comment or post you code if you need any further help.

Edit: I just re-read the question. If you are having trouble distinguishing single click from long click, you will need to use onKeyDown and onKeyUp and check the duration of the click. Esentially you will start a timer in the onKeyDown and check the time in the onKeyUp. You will have to watch for FLAG_CANCELED.

Further Edit: I found the time to do a couple of tests. This code should do what you want (onKeyUp() gets only short press events and onLongPress() gets only long press events).

The key thing here is in the call to event.startTracking() in the onKeyDown() handler.

Place in Activity (this should also work in a custom view as well but untested):

@Override
public boolean onKeyLongPress(int keyCode, KeyEvent event) {
    if (keyCode == KeyEvent.KEYCODE_MENU) {
        // Handle Long Press here
        Log.i("KeyCheck", "LongPress");
        return true;    
    }
    return super.onKeyLongPress(keyCode, event);
}
@Override   
public boolean onKeyDown(int keyCode, KeyEvent event) {
    Log.i("KeyCheck", "KeyDown" + keyCode);
    if (keyCode == KeyEvent.KEYCODE_MENU) {
        event.startTracking(); //call startTracking() to get LongPress event
        return true;
    }
    return super.onKeyDown(keyCode, event);
}
@Override
public boolean onKeyUp(int keyCode, KeyEvent event) {
    if (keyCode == KeyEvent.KEYCODE_MENU && event.isTracking()
            && !event.isCanceled()) {
        // handle regular key press here
        Log.i("KeyCheck", "KeyUp");
        return true;
    }
    return super.onKeyUp(keyCode, event);
}


来源:https://stackoverflow.com/questions/10867033/how-to-access-menu-button-onlongclick-in-android

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