onKeyDown() 问题
我想创建一个照片/视频捕获应用程序。
我创建了一个 CaptureView 类,它扩展了 SurfaceView 并将其放置在主窗体中。
主窗体的活动有 onCreateOptionsMenu()
方法来创建菜单。 菜单工作正常,但后来我尝试实现一个方法 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);
}
菜单不再出现,并且该方法没有捕获 onKeyDown 事件。
有谁知道这个问题的原因是什么?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(8)
我遇到了类似的问题,并通过添加
SurfaceView 子类的构造函数来解决它。
I had a similar problem and solved it by adding
in the constructor of my SurfaceView subclass.
我发现我为所有事件返回
true
,而我应该只为我正在使用的代码返回它。 我将 return true 移至if
语句的范围内,并返回false
否则,这使我的菜单恢复了!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 theif
statement and returnedfalse
otherwise That brought my menu back!我解决了删除 if 语句的问题,如下所示:
i solved removing the if statement, like this:
我不知道为什么有时它不起作用,但对于我的一个应用程序来说,这个
keyDown()
工作正常,当我将它用于新应用程序时,它又不起作用。但我有一个始终有效的解决方案:
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:
我通过在构造函数中添加以下代码解决了这个问题:
谢谢, Ciryon
每次我使用
setContentView(myView);
我必须调用myView.requestFocus();
。 如果有更好的解决方案请告诉我。I solved this by adding into constructor this code:
thanks, Ciryon
Also every time I use
setContentView(myView);
I must callmyView.requestFocus();
. If there is a better solution please tell me.嗯,在查看 API 文档时,唯一突出的是必须设置 android:clickable 属性以及启用 onKeyDown(...) 方法才能工作的视图。
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.
你可以试试这个
you can try this
您的 Activity 可能会吃掉关键事件。 重写活动中的 onKeyDown 并在其中抛出一个断点。
另外:当你说你已经“将其放置在主窗体中”时,你是使用 XML 布局还是在代码中执行操作?
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?