Android Fragments 片段已添加,对话片段?

fae0ux8s  于 2022-11-24  发布在  Android
关注(0)|答案(3)|浏览(205)

我有一个dialogfragment,它显示的很好,但有时当我试图显示它时,我总是得到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(), "");
}
2nbm6dog

2nbm6dog1#

片段事务是异步的。
在执行片段事务之前,可能有两次或多次调用此代码。!selectPlan04Dialog.isVisible() & !selectPlan04Dialog.isAdded()条件为真,并且show()计划稍后执行另一个片段事务。
修复此问题的一些选项:

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

atmip9wb2#

在这里我的解决方案,我已经尝试点击显示对话框片段点击按钮多次和快速。

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();
        }
bvjxkvbb

bvjxkvbb3#

modalBottomSheet.show(supportFragmentManager.beginTransaction().remove(modalBottomSheet),ModalBottomSheet.TAG)

“就像这样"

相关问题