简体   繁体   English

如何销毁Backstack上的片段?

[英]How to destroy a Fragment that is on Backstack?

I am trying to implement a method where I want to return to the previous fragment and destroy the current one. 我正在尝试实现一种方法,我想返回上一个片段并销毁当前片段。 However, when I add the fragment to the Backstack it doesn't get destroyed anymore afterwards. 但是,当我将片段添加到Backstack后,它不再被销毁了。

Is there any way to destroy it? 有什么办法可以销毁它吗? Or maybe to return to the previous fragment without using the Backstack? 还是不使用Backstack返回上一个片段?

Edit: I want to use the backwards navigation as well. 编辑:我也想使用向后导航。

Firstly if you are using the BackStack, it is not typical to need to specifically manually remove Fragments, which suggests you might want to have another think about your design. 首先,如果您使用的是BackStack,通常不需要专门手动删除Fragments,这表明您可能需要对设计进行其他考虑。

That said, to specifically manually remove a Fragment, Override onBackPressed in your Activity which is showing the Fragments, manually remove the Fragment there. 也就是说,要专门手动删除一个片段, onBackPressed在显示片段的Activity中重写onBackPressed在此处手动删除该片段。

To make it easy to determine which Fragment is currently showing, you can give it a Tag when you show it. 为了易于确定当前正在显示哪个片段,可以在显示它时给它一个标签。 For example: 例如:

fragTrans.replace(android.R.id.content, myFragment, "MY_FRAGMENT_X");

Then in the onBackPressed function of your Activity 然后在您的Activity的onBackPressed函数中

@Override
public void onBackPressed() 
{

    FragmentManager fragMan = getFragmentManager();

    // Check if that Fragment is currently visible
    MyFragment myFragment = (MyFragment)fragMan.findFragmentByTag("MY_FRAGMENT_X");
    boolean myFragXwasVisible = myFragment.isVisible();

    // Let the Activity pop the BackStack as normal
    super.onBackPressed();

    // If it was your particular Fragment that was visible...
    if (myFragXwasVisible) 
    {
        FragmentTransaction trans = fragMan.beginTransaction();
        trans.remove(myFragment).commit();
    }
}

Note: When it comes to specifically destroying your Fragment object, that is what Java's garbage collection is for. 注意:在专门销毁 Fragment对象时,这就是Java的垃圾回收的目的。 You don't need to worry about that yourself, Java will take care of destroying it when it needs to. 您无需担心自己,Java会在需要时将其销毁。 That's the whole point. 这就是重点。

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

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