如何在KeyboardKey上捕获onKeyLongPress。下面的代码只有当我把";KEYCODE_VOLUME_DOWN";或";"KEYCODE_VOLUME_UP";而不是";KEYCODE_Q";。我还试着写";113〃;而不是";KeyEvent.KEYCODE_Q";,但这无济于事。
(如果您需要XML,请询问。)
@Override
public boolean onKeyLongPress(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_Q) {
shortPress = false;
Toast.makeText(this, "longPress", Toast.LENGTH_SHORT).show();
return true;
}
return false;
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_Q) {
if(event.getAction() == KeyEvent.ACTION_DOWN){
event.startTracking();
if(event.getRepeatCount() == 0){
shortPress = true;
}
return true;
}
}
return super.onKeyDown(keyCode, event);
}
@Override
public boolean onKeyUp(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_G) {
if(shortPress){
Toast.makeText(this, "shortPress", Toast.LENGTH_SHORT).show();
}
shortPress = false;
return true;
}
return super.onKeyUp(keyCode, event);
}
对于软键盘,您应该像其他应用程序一样使用适当的计时器来处理长按事件。LatinIME也使用此解决方案,请查看。
PointerTracker.onDownEventInternal.startLongPressTime()
我的长按空格键的解决方案。
private long ms_press;
...
@Override
public void onPress( int i ){
ms_press = System.currentTimeMillis();
}
...
@Override
public void onKey( int primaryCode, int[] keyCodes) {
if( primaryCode == 32 && (System.currentTimeMillis()-ms_press) >= 1000 ){
//long press on Space key
}else{
//...
}
}