Android DialogFragment 遇到 java.lang.IllegalStateException: Fragment already added: 的解决方法

使用AppCompatDialogFragment 或者 DialogFragment 的过程中遇到java.lang.IllegalStateException: Fragment already added: 的解决方法:

private CountryChooseDialog mCountryChooseDialog;
private void showCountryChooseDialog() {
    if (mCountryChooseDialog == null) {
      mCountryChooseDialog = CountryChooseDialog.newInstance();
    }
    if (mCountryChooseDialog.isAdded()) {  //解决方法就是添加这行代码,如果已经添加了,就移除掉然后再show,就不会出现Fragment already added的错误了。
      getSupportFragmentManager().beginTransaction().remove(mCountryChooseDialog).commit();
    }
    mCountryChooseDialog.show(getSupportFragmentManager(), mCountryChooseDialog.getClass().getName());
}
posted @ 2021-01-08 00:13  ganzhijie  阅读(676)  评论(0编辑  收藏  举报