Reputation: 66555
I would like to create a photo/video capture application.
I have created a CaptureView
class which extends SurfaceView
and placed it in the main form.
The main form's activity has onCreateOptionsMenu()
method which creates a menu. The menu worked fine but then I tried to implement a method onKeyDown
:
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if(event.getAction() == KeyEvent.ACTION_DOWN) {
switch(keyCode) {
case KeyEvent.KEYCODE_CAMERA:
videoPreview.TakePicture();
return true;
}
}
return super.onKeyDown(keyCode, event);
}
The menu doesn't appear anymore and the method doesn't catch onKeyDown event.
Does anyone know what could be the reason for this issue?
Upvotes: 13
Views: 53791
Reputation:
I found that I was returning true
for all events, where I should only have been returning it for the code that I was using. I moved the return true inside the scope of the if
statement and returned false
otherwise That brought my menu back!
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
super.onKeyDown(keyCode, event);
if (keyCode == KeyEvent.KEYCODE_BACK) {
dba.close();
Intent result = new Intent("Complete");
setResult(Activity.RESULT_OK, result);
finish();
return true;
}
return false;
}
Upvotes: 12
Reputation: 962
I don't know why sometimes it does not work, though for one of my apps this keyDown()
is working fine and again when I use it for a new app then it does not work.
But I have a solution which always works:
@Override
public boolean dispatchKeyEvent (KeyEvent event) {
if (event.getAction()==KeyEvent.ACTION_DOWN && event.getKeyCode()==KeyEvent.KEYCODE_BACK) {
Toast.makeText(this, "Back button pressed", Toast.LENGTH_LONG).show();
return true;
}
return false;
}
Upvotes: 4
Reputation: 4171
I solved this by adding into constructor this code:
setFocusable(true);
requestFocus();
thanks, Ciryon
Also every time I use setContentView(myView);
I must call myView.requestFocus();
. If there is a better solution please tell me.
Upvotes: 2
Reputation: 143
i solved removing the if statement, like this:
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
switch(keyCode)
{
case KeyEvent.KEYCODE_CAMERA:
videoPreview.TakePicture();
return true;
}
return super.onKeyDown(keyCode, event);
}
Upvotes: 6
Reputation: 2777
I had a similar problem and solved it by adding
this.requestFocus();
this.setFocusableInTouchMode(true);
in the constructor of my SurfaceView subclass.
Upvotes: 14
Reputation: 11313
Your Activity could be eating the key event. Override onKeyDown in the activity and throw a breakpoint in there.
Also: when you say you've "placed it in the main form" are you using the XML layout or doing in your code?
Upvotes: 0
Reputation: 939
Well, in looking at the API documentation the only thing that stands out is that the android:clickable attribute must be set as well as the view being enabled for the onKeyDown(...) method to work.
Upvotes: 1