【问题标题】:How to prevent a fragment from being added multiple times?如何防止一个片段被多次添加?
【发布时间】:2012-12-11 19:52:31
【问题描述】:

当点击按钮等 UI 元素时,通常会将 Fragment 添加到布局中。如果用户非常快速地多次点击按钮,可能会发生多次添加 Fragment 的情况,从而导致各种问题。

如何预防?

【问题讨论】:

    标签: android android-fragments android-ui android-button


    【解决方案1】:

    我创建了一个辅助方法,确保仅在片段不存在时才添加它:

    public static void addFragmentOnlyOnce(FragmentManager fragmentManager, Fragment fragment, String tag) {
        // Make sure the current transaction finishes first
        fragmentManager.executePendingTransactions();
    
        // If there is no fragment yet with this tag...
        if (fragmentManager.findFragmentByTag(tag) == null) {
            // Add it
            FragmentTransaction transaction = fragmentManager.beginTransaction();
            transaction.add(fragment, tag);
            transaction.commit();
        }
    }
    

    来自 Activity 或另一个 Fragment 的简单调用:

    addFragmentOnlyOnce(getFragmentManager(), myFragment, "myTag");
    

    这适用于 android.app.* 和 android.support.app.* 包。

    【讨论】:

    • 请注意,如果对话框以非常快的速度连续显示,例如在不到 10 毫秒的时间内显示两次,则答案中的方法不起作用。原因是经典的多线程问题“check-then-act”。这个问题没有通用的解决方案,你必须使用某种同步来自己做饭。
    • 它对我有用,伙计,非常感谢!
    【解决方案2】:

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

                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");
                }
    

    【讨论】:

      猜你喜欢
      • 2016-02-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-01-23
      • 1970-01-01
      • 1970-01-01
      • 2015-12-05
      • 2017-07-05
      相关资源
      最近更新 更多