Skip to content

Instantly share code, notes, and snippets.

@cesclong
Created April 5, 2021 08:01
Show Gist options
  • Save cesclong/9fd8a8b61387d648d42d48669de95fce to your computer and use it in GitHub Desktop.
Save cesclong/9fd8a8b61387d648d42d48669de95fce to your computer and use it in GitHub Desktop.
Fix `DialogFragment` crash questions ... 修复DialogFragment崩溃崩溃的
import androidx.fragment.app.DialogFragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;
import org.jetbrains.annotations.NotNull;
import java.lang.reflect.Field;
/**
* Fix `DialogFragment` crash questions ... <br /><br />
*
* <p>
* Including the following questions <br />
* <ul>
* <li> java.lang.IllegalStateException: Fragment already added: DialogFragment </li>
* <p>
* 出现场景: 重复调用show()方法时 <br />
* 解决方法: 显示前先判断有没有添加过
* <p/>
* <li> java.lang.IllegalStateException: Can not perform this action after onSaveInstanceState </li>
* <p>
* 出现场景: 当此DialogFragment的show()方法执行是在其所在Activity被销毁后,就会出现此问题 <br />
* 解决方法: 通过反射实现show()方法逻辑,允许其状态丢失
* </p>
* </ul>
*
* </p>
*
* <p>
* Reference article <br />
* <ul>
* <li> https://blog.csdn.net/kifile/article/details/47442899 </li>
* <li> https://blog.csdn.net/baidu_28027209/article/details/79740209 </li>
* </ul>
*
* </p>
*/
public class FixCrashWithDialogFragment extends DialogFragment {
@Override
public void show(@NotNull FragmentManager manager, String tag) {
try {
manager.executePendingTransactions();
if (!isAdded()) {
showAllowingStateLoss(manager, tag);
}
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Show Dialog Allowing State Loss
*
* @param manager {@link FragmentManager}
* @param tag TAG
*/
public void showAllowingStateLoss(@NotNull FragmentManager manager, String tag) {
try {
Class<?> superclass = this.getClass().getSuperclass();
if (null != superclass) {
Field mDismissed = superclass.getDeclaredField("mDismissed");
Field mShownByMe = superclass.getDeclaredField("mShownByMe");
mDismissed.setAccessible(true);
mShownByMe.setAccessible(true);
mDismissed.setBoolean(this, false);
mShownByMe.setBoolean(this, true);
}
} catch (NoSuchFieldException | IllegalAccessException e) {
e.printStackTrace();
}
FragmentTransaction ft = manager.beginTransaction();
ft.add(this, tag);
ft.commitAllowingStateLoss();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment