只显示一次DialogFragment

4

当给定的回调被调用时,我希望向用户显示一个DialogFragment。问题是有时监听器会同时多次调用,而fragmentmanager会显示多个fragment。我正在使用以下代码:

    if (getSupportFragmentManager().findFragmentByTag("testFragment") == null) {
        getSupportFragmentManager().beginTransaction()
                .add(new MyFragment(), "testFragment")
                .commit();
        Log.e("TAG", "Show! "+(getSupportFragmentManager()
                    .findFragmentByTag("testFragment") == null));
    } 

正如最后一行的日志信息所示,在提交FragmentTransaction之后,有一个短暂的时间段,findFragmentByTag返回null。那么,有没有比保存上次调用的毫秒时间并在第二次调用时忽略更优雅的方法来确保仅显示一次消息呢?

1个回答

12

在你提交(commit)后立即调用getSupportFragmentManager().executePendingTransactions()应该可以强制要求片段管理器立即提交(fragment),这样对findFragmentByTag("testFragment")的后续调用就不再返回null了。


1
这并不总是起作用的。如果出现 java.lang.IllegalStateException: Recursive entry to executePendingTransactions 异常,它将显示 2(或更多)。 - neteinstein

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接