在DialogFragment 的子类中,调用
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// 保存整个实例
setRetainInstance(true);
}
期望结果是 弹出dialog,在屏幕旋转后,保持弹出状态,
但是未弹出,原因是
Dialog
public void dismiss() {
if (Looper.myLooper() == mHandler.getLooper()) {
dismissDialog();
} else {
mHandler.post(mDismissAction);
}
}
void dismissDialog() {
...
sendDismissMessage();
...
}
// 使用handler调用onDismiss
private void sendDismissMessage() {
if (mDismissMessage != null) {
// Obtain a new message so this dialog can be re-used
Message.obtain(mDismissMessage).sendToTarget();
}
}
屏幕旋转后,looper执行 ReLaunchActivity,在ReLaunchActivity中执行
fragment的onDestroyView(),而DialogFragment 中
@Override
public void onDestroyView() {
super.onDestroyView();
if (mDialog != null) {
// Set removed here because this dismissal is just to hide
// the dialog -- we don't want this to cause the fragment to
// actually be removed.
mViewDestroyed = true;
mDialog.dismiss();
mDialog = null;
}
}
执行了 mDialog.dismiss();mDialog向looper发送message,
当ReLaunchActivity执行完之后,fragment attath到acitivity中,然后Looper执行下一个msg,就执行到
DialogFragment 的onDismiss中,而在
DialogFragment 中,调用了 dismissInternal(true);
@Override
public void onDismiss(DialogInterface dialog) {
if (!mViewDestroyed) {
// Note: we need to use allowStateLoss, because the dialog
// dispatches this asynchronously so we can receive the call
// after the activity is paused. Worst case, when the user comes
// back to the activity they see the dialog again.
dismissInternal(true);
}
}
dismissInternal 又调用了remove,DialogFragment 又从activity中移除,所以,dialog不会保持弹出状态
解决办法:
重写DialogFragment 的onDismiss方法
@Override
public void onDismiss(DialogInterface dialog) {
LegoLog.d("dialog onDismiss");
}
但是不建议这样做,还是不要使用 setRetainInstance(true);的方式,因为会导致内存泄漏