试图为onKeyDown事件创建自己的方法(Android)

时间:2011-01-29 17:35:40

标签: java android sdk onkeydown

我有两个班级:

MainPanel(我定义了一些方法) MainThread(我使用这些方法循环创建经典游戏结构)

在MainPanel类中,我有这个方法来捕获是否按下了一个键

 @Override 
 public boolean onKeyDown(int keyCode, KeyEvent event) { 
         switch(keyCode) { 
                 case KeyEvent.KEYCODE_DPAD_UP: 
                         Log.i(TAG,"key up was pressed"); 
                         return true; 
         } 
         return false; 
}

它工作正常,我的问题是,是否可以将onKeyDown创建为正确的方法并在循环中使用它来避免监听器。我们的想法是在MainPanel中定义一个这样的方法:

public void myOwnOnKeyDown(int keyCode, KeyEvent event) { 
     switch(keyCode) { 
             case KeyEvent.KEYCODE_DPAD_UP: 
                     Log.i(TAG,"key up was pressed");
     }
}

然后,将它调用到MainThread类的循环中,就像这样......

public class MainThread extends Thread {
//...

public void loop() { 
    Canvas canvas; 
    KeyEvent event; Log.d(TAG, "Starting game loop");

    while (running) {

        this.MainPanel.MyOwnOnKeyDown(keyCode, event); 
        this.MainPanel.moveElements(); 
        this.MailPanel.drawElements(canvas); 
    } 
}

在以下行我不知道如何传递参数keyCode ...

this.MainPanel.MyOwnOnKeyDown(keyCode, event); 

有可能吗?

提前致谢

2 个答案:

答案 0 :(得分:3)

看起来你正在尝试创作游戏或其他类似类型的程序。

在主循环中,你试图调用自己的keydown方法,你应该调用像“handleInput()”这样的方法,然后你真正的Android keydown方法的实现应该添加事件信息(keycode)等)到队列集合。然后handleInput()方法将处理自上次循环以来已经发生的所有按键(在队列中)。

以下是游戏的主循环示例:

  public void run() {

    initializeState();

    while (stillRunning) { // stillRunning is a flag that signals the user wants to exit

      while(isPaused() && stillRunning) { // isPaused is a flag that is set in the if the user selects pause
        try {
          sleep(100);
        } catch (InterruptedException e) {
        }
      }
      if(!stillRunning)
        break;

      Canvas c = null;
      try {
        c = surfaceHolder.lockCanvas(null); // the game uses a Surface view for drawing
        synchronized (surfaceHolder) {
          updateState();  // update game entities - such as remove explosions that are finished, etc.
          handleInput(); // handle user input (key presses, screen touches, etc.)
          updatePhysics(); // collision detection, speed changes due to gravity, etc.
          updateAnimations(); // update which frames need to draw for animating entities
          updateSound(); // start/stop any sounds required by new game state/events
          updateVideo(c); // draw the next frame of video
        }
      } finally {
        // do this in a finally so that if an exception is thrown
        // during the above, we don't leave the Surface in an
        // inconsistent state
        if (c != null) {
          surfaceHolder.unlockCanvasAndPost(c);
        }
      }
    }
  }

具有此循环的类还有一个队列,用于保存来自播放器的所有事件:

private ConcurrentLinkedQueue<GameEvent> eventQueue = new ConcurrentLinkedQueue<GameEvent>();

“GameEvent”类有一个时间戳记(当事件发生时)。然后是子类,如KeyGameEvent(用于键盘事件)和TouchGameEvent(用于屏幕触摸),ScrollGameEvent,LongPressGameEvent(TouchGameEvent的子类)等。

以下是一个例子:

public class KeyGameEvent extends GameEvent {

  public int keyCode;
  public KeyEvent keyEvt;
  public boolean up;

  public KeyGameEvent(int keyCode, boolean keyUp, KeyEvent evt) {
    this.keyCode = keyCode;
    this.up = keyUp;
    this.keyEvt = evt;
  }

}

然后将这些GameEvent类实例化并放置在标准Android事件处理程序方法的队列中,例如:

  public boolean onKeyDown(int keyCode, KeyEvent event) {
    KeyGameEvent kge = new KeyGameEvent(keyCode, false, evt);
    eventQueue.add(kge);
    return true;
  }

  public boolean onKeyUp(int keyCode, KeyEvent event) {
    KeyGameEvent kge = new KeyGameEvent(keyCode, true, evt);
    eventQueue.add(kge);
    return true;
  }

  public void onLongPress(MotionEvent evt) {
    LongPressGestureGameEvent lpe = new LongPressGestureGameEvent(evt);
    eventQueue.add(lpe);
  }

最后,handleInput()方法如下所示:

  private void handleInput() {

    while(true) {
      GameEvent evt = eventQueue.poll();
      if(evt == null)
        break;

      if(evt instanceof KeyGameEvent) {
        processKeyGameEvent((KeyGameEvent)evt);
      }
      else if(evt instanceof TouchGameEvent) {
        processTouchGameEvent((TouchGameEvent)evt);
      }
      // ... etc. for the different types of events.
    }
  }

显然(我希望)在由handeInput()调用的processKeyGameEvent()等方法中,你实际上检查了哪些键是被按下/释放的,并让你的游戏逻辑做任何适合这种按键操作的东西/释放。

如果您的游戏只对键盘输入事件感兴趣(而不是触摸等),那么您可以放弃创建GameEvent类层次结构,只需将onKeyDown()接收的KeyEvent放入队列即可。

答案 1 :(得分:1)

我认为你想要做的是设置一个变量,如果一个键是活动的,并在你的主循环引用中。

例如:在MainPanel中有一些类字段,例如:

// some constants
static int NONE = 0;
static int UP = 1;
static int DOWN = 2;
static int LEFT = 3;
static int RIGHT = 4;
// state fields
private volatile int movement = NONE;
private volatile boolean jumping = false;

然后你的onKeyDown看起来类似于:

@Override 
 public boolean onKeyDown(int keyCode, KeyEvent event) { 
         switch(keyCode) { 
                 case KeyEvent.KEYCODE_DPAD_UP: 
                         Log.i(TAG,"key up was pressed");
                         movement = UP;
                         return true; 
         } 
         return false; 
}

和onKeyUp看起来类似于:

@Override 
 public boolean onKeyDown(int keyCode, KeyEvent event) { 
         switch(keyCode) { 
                 case KeyEvent.KEYCODE_DPAD_UP: 
                         Log.i(TAG,"key up was pressed");
                         movement = NONE;
                         return true; 
         } 
         return false; 
}

你的主循环看起来像:

while (running) {
    if (this.movement == UP) {
         // update stuff
    } else if (this.movement == DOWN) {
         // update other stuff
    } // etc ...
    this.MainPanel.moveElements(); 
    this.MailPanel.drawElements(canvas); 
}

您可能需要更复杂的逻辑来跟踪按键操作,但这会将按钮事件与更新分开,以便您可以持续移动。