片段已添加,dialogfragment?

时间:2019-04-10 13:04:23

标签: android android-fragments android-dialogfragment illegalstateexception fragmentmanager

我有一个显示很好的对白片段,但是当我尝试显示它时,我不断得到IllegalStateException

下面是logcat

java.lang.IllegalStateException: Fragment already added: SelectPlan04Dialog{fa768dc #7 }
    at android.support.v4.app.FragmentManagerImpl.addFragment(FragmentManager.java:1893)
    at android.support.v4.app.BackStackRecord.executeOps(BackStackRecord.java:760)
    at android.support.v4.app.FragmentManagerImpl.executeOps(FragmentManager.java:2595)
    at android.support.v4.app.FragmentManagerImpl.executeOpsTogether(FragmentManager.java:2382)
    at android.support.v4.app.FragmentManagerImpl.removeRedundantOperationsAndExecute(FragmentManager.java:2337)
    at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:2244)
    at android.support.v4.app.FragmentManagerImpl$1.run(FragmentManager.java:702)
    at android.os.Handler.handleCallback(Handler.java:790)
    at android.os.Handler.dispatchMessage(Handler.java:99)
    at android.os.Looper.loop(Looper.java:192)
    at android.app.ActivityThread.main(ActivityThread.java:6679)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:826)]

这是我调用对话框的代码

if (selectPlan04Dialog == null) {
    selectPlan04Dialog = new SelectPlan04Dialog();
}
if (!selectPlan04Dialog.isVisible() && !selectPlan04Dialog.isAdded()) {
    Bundle b = new Bundle();
    b.putSerializable("moduleApi", module);
    selectPlan04Dialog.setArguments(b);                
    selectPlan04Dialog.show(getCurrentActivity().getSupportFragmentManager(), "");
}

2 个答案:

答案 0 :(得分:2)

这是我的解决方案,我尝试通过多次快速点击按钮来单击显示对话框片段。

        try{
            FragmentManager fm = getSupportFragmentManager();
            Fragment oldFragment = fm.findFragmentByTag("wait_modal");

            if(oldFragment != null && oldFragment.isAdded())
                return;

            if(oldFragment == null && !please_wait_modal.isAdded() && !please_wait_modal.isVisible()){
                fm.executePendingTransactions();
                please_wait_modal.show(fm,"wait_modal");
            }
        }catch (Exception e){
            e.printStackTrace();
        }

答案 1 :(得分:0)

片段事务是异步的。

在执行片段事务之前,可能有两个或两个以上对此代码的调用。 !selectPlan04Dialog.isVisible() & !selectPlan04Dialog.isAdded()条件为true,并且show()安排另一个片段事务以稍后执行。

一些解决此问题的方法:

  • 每次都创建一个新对话框,不要尝试重用旧对话框
  • 将异步片段事务更改为与片段管理器executePendingTransactions()的调用同步