How To Differentiate Between Long Key Press And Regular Key Press?
Solution 1:
The reason why onKeyLongPress is never called, is that you return true in onKeyDown without telling the framework that this might be a long press - causing the KeyEvent to stop its flow through the different event handlers.
What you need to do is this:
- Before you return true, call
event.startTracking()as explained in the documentation. - Handle the long press in
onKeyLongPress.
Implement as below and it will work:
@OverridepublicbooleanonKeyDown( int keyCode, KeyEvent event ) {
if( keyCode == KeyEvent.KEYCODE_BACK ) {
event.startTracking();
returntrue;
}
returnsuper.onKeyDown( keyCode, event );
}
@OverridepublicbooleanonKeyUp( int keyCode, KeyEvent event ) {
if( keyCode == KeyEvent.KEYCODE_BACK ) {
//Handle what you want on short press. returntrue;
}
returnsuper.onKeyUp( keyCode, event );
}
@OverridepublicbooleanonKeyLongPress( int keyCode, KeyEvent event ) {
if( keyCode == KeyEvent.KEYCODE_BACK ) {
//Handle what you want in long press.returntrue;
}
returnsuper.onKeyLongPress( keyCode, event );
}
Solution 2:
Why not use onKeyUp() as well as onKeyDown()? During onKeyDown() you do not know whether it is a long press or not, because that is called as soon as the key is pressed and you do not know how long the user intends to hold the key down for. As KasperMoerch correctly says, you need to call startTracking in your onKeyDown() method, and return true. Then in your onKeyUp() you can call event.isTracking() and event.isLongPress() to determine whether to handle things as a long press or short press.
Solution 3:
I think the best way to handle it is as such.
The only downside I can see here, is that single clicking the menu button doesn't make a sound in case the user has it enabled. Maybe there is a way to check this setting and use it, or call the default behavior.
Code:
privateboolean _handledMenuButton=false;
@OverridepublicbooleanonKeyUp(finalint keyCode,final KeyEvent event) {
switch(keyCode) {
case KeyEvent.KEYCODE_MENU:
if (!_handledMenuButton) {
//Handle single clicking here
}
_handledMenuButton=false;
returntrue;
}
returnsuper.onKeyUp(keyCode,event);
}
@OverridepublicbooleanonKeyLongPress(finalint keyCode, final KeyEvent event) {
switch(keyCode) {
case KeyEvent.KEYCODE_MENU:
//Handle long clicking here
_handledMenuButton=true;
returntrue;
}
returnsuper.onKeyLongPress(keyCode,event);
}
@OverridepublicbooleanonKeyDown(finalint keyCode,final KeyEvent event) {
switch(keyCode) {
case KeyEvent.KEYCODE_MENU:
_handledMenuButton=false;
event.startTracking();
returntrue;
}
returnsuper.onKeyDown(keyCode,event);
}
Post a Comment for "How To Differentiate Between Long Key Press And Regular Key Press?"