美文网首页
通过KeyEvent.Callback和Window.Callb

通过KeyEvent.Callback和Window.Callb

作者: 程树欣 | 来源:发表于2016-08-01 16:20 被阅读909次
    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.Callb

          本文链接:https://www.haomeiwen.com/subject/vmoxsttx.html