前几天在通过DecorView添加自定义IOSDialog的时候,无法实现按返回键关闭dialog,究其原因呢就是window的事件响应在Activity上而不在自定义的View上,解决办法呢就是实现KeyEvent.Callback
和Window.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);
}
}
}
网友评论