如何区分长按键preSS和定期关键preSS区别? [英] How to differentiate between long key press and regular key press?
问题描述
我试图重写的返回键preSS的功能。当用户presses一次,我希望它回来了previous屏幕。然而,当返回键是长期pressed(对,比方说,2秒以上),我想退出应用程序。
I'm trying to override the functionality of the back key press. When the user presses it once, I want it to come back to the previous screen. However, when the back key is long-pressed (for, let's say, two seconds or more), I want to exit the application.
到现在为止,我已经重写我的活动这两种方法:
By now, I have overriden these two methods in my activity:
@Override
public boolean onKeyDown( int keyCode, KeyEvent event){
if (keyCode == KeyEvent.KEYCODE_BACK) {
//manage short keypress
return true;
}
return super.onKeyDown(keyCode, event);
}
@Override
public boolean onKeyLongPress( int keyCode, KeyEvent event){
if (keyCode == KeyEvent.KEYCODE_BACK) {
//manage long keypress (different code than short one)
return true;
}
return super.onKeyLongPress(keyCode, event);
}
但 onKeyLong preSS
回调不会被调用,因为事件总是收到的onkeydown
方法。
But the onKeyLongPress
callback is never called, because the event is always received by the onKeyDown
method.
有什么办法有两种方法工作的?抑或是做所有的的onkeydown
和使用的重复/毫秒的数量来检测呢?
Is there any way of having both methods working? Or has it to be done all in the onKeyDown
and use the number of repetitions/milliseconds to detect it?
推荐答案
之所以 onKeyLong preSS
不会被调用,是您在<$返回true C $ C>的onkeydown 瞒着,这可能是一个漫长的preSS框架 - 造成的KeyEvent通过不同的事件处理程序,以阻止其流动
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.
您需要做的是这样的:
- 在你返回true,调用
event.startTracking()
在解释<一个href="http://developer.android.com/reference/android/view/KeyEvent.Callback.html#onKeyLong$p$pss%28int,%20android.view.KeyEvent%29">documentation. - 在处理长preSS在
onKeyLong preSS
。
- Before you return true, call
event.startTracking()
as explained in the documentation. - Handle the long press in
onKeyLongPress
.
实现如下,它会工作:
@Override
public boolean onKeyDown( int keyCode, KeyEvent event ) {
if( keyCode == KeyEvent.KEYCODE_BACK ) {
event.startTracking();
return true;
}
return super.onKeyDown( keyCode, event );
}
@Override
public boolean onKeyUp( int keyCode, KeyEvent event ) {
if( keyCode == KeyEvent.KEYCODE_BACK ) {
//Handle what you want on short press.
return true;
}
return super.onKeyUp( keyCode, event );
}
@Override
public boolean onKeyLongPress( int keyCode, KeyEvent event ) {
if( keyCode == KeyEvent.KEYCODE_BACK ) {
//Handle what you want in long press.
return true;
}
return super.onKeyLongPress( keyCode, event );
}
这篇关于如何区分长按键preSS和定期关键preSS区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!