0

I need to attach custom touch and hardware key handling to a SurfaceView. I need to use separate listeners (rather than adding the dispatchKeyEvent() and dispatchTouchEvent() methods to the SurfaceView), as I will be providing the custom event handling functionality to a third party to use on their SurfaceView, and I want to keep it separate.

My custom touch event handler works fine, but the key event handler doesn't catch any events. Here's how I'm setting them:

public MyGLSurfaceView(Context c, AttributeSet a) {
    // Other setup...
    setOnTouchListener(new MyTouchListener()); // Works
    setOnKeyListener(new MyKeyListener()); // No events captured

}

And here's my key listener:

public class MyKeyListener implements View.OnKeyListener {
    @Override
    public boolean onKey(View v, int key, KeyEvent e) {
        System.out.println("A hardware key was pressed!");
        return true;
    }
}

Should I be attaching the key listener to a different object than the SurfaceView? The view sits inside a Dialog, so could I attach my key listener to that instead?

Dan Halliday
  • 725
  • 6
  • 22

1 Answers1

2

By default, the SurfaceView is not focusable and then doesn't broadcast keyevent. You need to activate focus :

setFocusable(true);
setFocusableInTouchMode(true);
requestFocus();
//And now you set your OnKeyEventListener

Be aware that by loosing the focus for another view, this one will not receive any events until it receives the focus again.

NitroG42
  • 5,336
  • 2
  • 28
  • 32