views:

783

answers:

3

Hi,

I am creating a custom Widget which extends SurfaceView and I am planning to use it for camera preview.

In the main activity I tried to implement some event listeners but can't catch any event.

This is the part of code where I tried to add an event listener:

videoPreview = (CaptureView)findViewById(R.id.capturePreview);

    videoPreview.setOnKeyListener(new OnKeyListener(){
  public boolean onKey(View v, int keyCode, KeyEvent event){
   switch(keyCode)
   {
   case KeyEvent.KEYCODE_CAMERA:
    videoPreview.TakePicture();
    return true;
   }
   return false;
  }
 });

If I press a button the LogCat outputs "Continuing to wait for key to be dispatched" line.

Does anyone know how to implement event listeners in main activity using SurfaceView classes?

Thanks!

+1  A: 

I'm not sure if this is the answer you're looking for, but it might be worth trying.

The OnKeyListener for a specific View will only be called if the key is pressed while that View has focus. You could try ensuring that it has focus with:

videoPreview.requestFocus();

or put the OnKeyListener on the layout (eg LinearLayout) that contains everything else (including the CaptureView). Something like:

LinearLayout ll = (LinearLayout) findViewById(R.id.VideoContainer);
ll.setOnClickListener(new OnKeyListener(){
    public boolean onKey(View v, int keyCode, KeyEvent event) {
        // ...
    }
);
fiXedd
A: 

Since it appears that you have your own custom class setup named "CaptureView" you could also override View.onKeyDown and View.onKeyUp in your "CaptureView" class. This has always worked in my SurfaceView based games and allows you to do any extra processing that you may want to do in the time between the down and up event.

View.onKeyDown()

snctln
+1  A: 

The OnKeyListener for a specific View will only be called if the key is pressed while that View has focus. For a generic SurfaceView to be focused it first needs to be focusable:

view.setFocusable(true);
view.setFocusableInTouchMode(true);

And than you can make the view focused by calling requestFocus():

videoPreview.requestFocus();

After that your OnKeyListener will start receiving key events until some other view gets focus.

Honza