简体   繁体   English

当Activity在后台被破坏时,如何删除碎片

[英]When Activity is destroyed on background,how to remove fragment

When my app switches to background,the system memory is low, then android will destroy my activity.At that time,I want to remove the fragments attached to activity,so that when activity switches to foreground,I can avoid any abnormal behavior of that activity.I do it like this: 当我的应用程序切换到后台时,系统内存不足,则android会破坏我的活动。当时,我想删除附加到活动的片段,以便当活动切换到前台时,我可以避免该活动的任何异常行为活动。我这样做是这样的:

@Override
    public void onSaveInstanceState(Bundle outState) {
        FragmentManager fm = getSupportFragmentManager();
        AbstractBaseViewFragment previous = (AbstractBaseViewFragment) fm.findFragmentByTag(FRAGMENT_TAG);
        if (previous != null) {
            fm.beginTransaction().remove(previous).commitAllowingStateLoss();
            fm.executePendingTransactions();
        }
        super.onSaveInstanceState(outState);
    }

so I want to ask:Are there any other good ideas to finish this target?Will my method cause any crashes? 所以我想问:是否还有其他好主意可以完成此目标?我的方法会导致崩溃吗?

You can try this: ft.detach(previous); 您可以尝试以下操作: ft.detach(previous);

if (previous != null) {
                FragmentTransaction ft = fm.beginTransaction();
                ft.detach(previous);
                ft.remove(previous);
                ft.commitAllowingStateLoss();
... // the rest of your code
            }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM