我正在关注 Google 的 Touch Gestures有关检测方向键事件的指南,但它们似乎不起作用。
这是我的代码的一部分:
public final class ResultActivity extends Activity implements AsyncResponse{
[...]
@Override
public boolean onKeyUp(int keycode, KeyEvent event){
if(keycode == KeyEvent.KEYCODE_DPAD_DOWN){
//this doesnt get detected
return true;
}
if(keycode == 4){
//this gets detected
return true;
}
return false;
}//end onKeyUp
}//end activity
是的,我也尝试过onKeyDown。
什么可能导致此问题?
最佳答案
这并不能完全回答你的问题,但我认为这是一个很好的建议。当我尝试以这种方式检测 keyevent 时,我遇到了同样的问题。我只能正确注册其中两个事件。经过几天的摸索之后,我决定寻找其他选择,并找到了 GestureDetector,尝试了一下,效果非常好。您可以找到API docs here对于GestureDetector
。我还将自己提供一些代码来帮助您。
这是我在代码中使用GestureDetector
的方式。在最顶部,我声明了一个私有(private)的GestureDetector
:
private GestureDetector gestureDetector;
然后,在 onCreate()
方法中,我调用一个创建 GestureDetector
的方法(没有理由这样做而不是在onCreate()
方法 - 这样看起来更干净并且更有组织性):
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
...
gestureDetector = createGestureDetector(this);
}
createGestureDetector()
方法如下所示:
private GestureDetector createGestureDetector(Context context) {
GestureDetector gestureDetectorTemp = new GestureDetector(context, new GestureDetector.OnGestureListener() {
//we are creating our gesture detector here
@Override
public boolean onDown(MotionEvent motionEvent) {
return false;
}
@Override
public void onShowPress(MotionEvent motionEvent) {
}
@Override
public boolean onSingleTapUp(MotionEvent motionEvent) { //onTap
AudioManager am = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
am.playSoundEffect(SoundEffectConstants.CLICK); //if we tap once, play a click sound
return false;
}
@Override
public boolean onScroll(MotionEvent motionEvent, MotionEvent motionEvent2, float distanceX, float distanceY) {
return false; //this is the wrong kind of scroll
}
@Override
public void onLongPress(MotionEvent motionEvent) {
}
@Override
public boolean onFling(MotionEvent motionEvent, MotionEvent motionEvent2, float v, float v2) { //fling = a single slide
int dx = (int) (motionEvent2.getX() - motionEvent.getX()); //figure out the distance moved horizontally
int dy = (int) (motionEvent2.getY() - motionEvent.getY()); //figure out the distance moved vertically
//if dx > 0, moved forward, if dx < 0, moved backward
//if dy > 0, moved up, if dy < 0, moved down
return true;
}
});
return gestureDetectorTemp;
}
@Override
public boolean onGenericMotionEvent(MotionEvent event) {
if (gestureDetector != null) {
return gestureDetector.onTouchEvent(event);
}
return false;
}
您必须确保包含我在最后的 onGenericMotionEvent()
方法。这可以确保每次发生运动事件时您的 GestureDetector
都会收到通知。
最后要注意的是 GestureDetector
中的返回 - 返回 true 来消耗事件,返回 false 来不消耗事件。换句话说,如果你想覆盖默认发生的情况,比如向下滑动时关闭应用程序,只需进入 onFling()
事件,如果 dy < 0,则返回 true。这会消耗该事件,并且不会将其发送到其他默认方法来执行操作。
关于java - 未检测到 KeyEvent.KEYCODE_DPAD_CENTER,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27225758/