DialogFragment调用show()报Can not perform this action after onSaveInstanceState的解决办法

参考文章

解决办法一

PromptDialogFragment中重写show()dismiss()方法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
@Override
public void show(FragmentManager manager, String tag) {
//super.show(manager, tag);
try {
Class c = Class.forName("androidx.fragment.app.DialogFragment");
Field dismissed = c.getDeclaredField("mDismissed");
dismissed.setAccessible(true);
dismissed.set(obj, false);
Field shownByMe = c.getDeclaredField("mShownByMe");
shownByMe.setAccessible(true);
shownByMe.set(obj, false);
} catch (Exception e) {
NLog.e(Constants.TAG, Log.getStackTraceString(e));
}
FragmentTransaction ft = manager.beginTransaction();
ft.add(this, tag);
ft.commitAllowingStateLoss();
}

@Override
public void dismiss() {
//super.dismiss();
dismissAllowingStateLoss();
}

解决方法二

(1)自建包androidx.fragment.app,并在包下新建类MyDialogFragment继承DialogFragment

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
package androidx.fragment.app;

public class MyDialogFragment extends DialogFragment {

public boolean getDismissed() {
return mDismissed;
}

public void setDismissed(boolean dismissed) {
this.mDismissed = dismissed;
}

public boolean getShownByMe() {
return mShownByMe;
}

public void setShownByMe(boolean shownByMe) {
this.mShownByMe = shownByMe;
}
}

(2)在PromptDialogFragment中重写show()dismiss()方法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
public class LoginPromptDialogFragment extends MyDialogFragment

...

@Override
public void show(FragmentManager manager, String tag) {
setDismissed(false);
setShownByMe(false);
FragmentTransaction ft = manager.beginTransaction();
ft.add(this, tag);
ft.commitAllowingStateLoss();
}

@Override
public void dismiss() {
//super.dismiss();
dismissAllowingStateLoss();
}
}

Powered by AppBlog.CN     浙ICP备14037229号

Copyright © 2012 - 2020 APP开发技术博客 All Rights Reserved.

访客数 : | 访问量 :