通过KeyEvent.Callback和Window.Callback分发按键事件

Paste_Image.png

前几天在通过DecorView添加自定义IOSDialog的时候,无法实现按返回键关闭dialog,究其原因呢就是window的事件响应在Activity上而不在自定义的View上,解决办法呢就是实现KeyEvent.CallbackWindow.Callback

public class UIAlertView implements KeyEvent.Callback, Window.Callback {
  public UIAlertView(Context pContext) {
        if (!(pContext instanceof Activity)) {
            throw new RuntimeException("The context must is a Activity");
        }
        this.mContext = (Activity) pContext;
        xWindow = mContext.getWindow();
        //当dialog初始化的时候要占用activity 对keyevent的处理,否则无法监听返回事件
        xWindow.setCallback(this);
        viewRoot = (FrameLayout) xWindow.getDecorView().findViewById(android.R.id.content);
    }
 @Override
    public boolean dispatchKeyEvent(KeyEvent event) {
        //做事件分发
        if (xWindow.superDispatchKeyEvent(event)) {
            return true;
        }
        return event.dispatch(this, xWindow.getDecorView() != null
                ? xWindow.getDecorView().getKeyDispatcherState() : null, this);
    }
      ...
    private void dismiss() {
           ...
            //将焦点回交给activity
            if(xWindow!=null)xWindow.setCallback(mContext);
        }
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容