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