将View.OnKeyListener附加到SurfaceView [英] Attaching a View.OnKeyListener to a SurfaceView

查看:81
本文介绍了将View.OnKeyListener附加到SurfaceView的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要将自定义触摸和硬件键处理附加到SurfaceView.我需要使用单独的侦听器(而不是将dispatchKeyEvent()dispatchTouchEvent()方法添加到SurfaceView),因为我将向第三方提供自定义事件处理功能以在其SurfaceView上使用,并且希望将其分开.

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.

我的自定义 touch 事件处理程序工作正常,但是 key 事件处理程序无法捕获任何事件.这是我的设置方法:

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

}

这是我的主要倾听者:

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;
    }
}

我应该将键侦听器附加到与SurfaceView不同的对象吗?该视图位于Dialog内部,因此我可以将我的关键侦听器附加到该视图上吗?

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?

推荐答案

默认情况下,SurfaceView无法聚焦,因此不会广播关键事件. 您需要激活焦点:

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.

这篇关于将View.OnKeyListener附加到SurfaceView的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆