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

通过KeyEvent.Callback和Window.Callback分发按键事件_第1张图片
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);
        }
    }
}

你可能感兴趣的:(通过KeyEvent.Callback和Window.Callback分发按键事件)