简体   繁体   English

如何处理片段回栈

[英]How to handle fragment backstack

I'm having problem with fragment.我遇到片段问题。 Lets try to understand my issue, I have two fragment A and B .让我们试着理解我的问题,我有两个片段AB When app start with main activity,i start fragment A as you can see:当应用程序以主要活动启动时,我启动片段A ,如您所见:

 getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,new MusicFragment())
                .commit();

When i click on a button, it starts fragment B当我单击一个按钮时,它会启动片段B

 getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,new BarFragment())
                .addToBackStack(null)
                .commit();

Main problem is after starting fragment B ,when i pressed back to go back to fragment A , Fragment A Recreated with new state. Main problem是在启动片段B之后,当我按回 go 回到片段A时,片段A用新的 state 重新创建。 I don' want to recreate fragment A .我不想重新创建片段A I only want to start fragment from old state where i left.我只想从我离开的旧 state 开始片段。 How to fix it?如何解决?

Instead of calling the replace method you should be calling the add method with a subsequent call to addToBackStack with an argument of null .而不是调用replace方法,您应该调用add方法并随后调用addToBackStack ,参数为null The add method adds the fragement to the stack with a null tag and calling the addToBackStack with an argument of null then the current fragment is stopped upon commit. add方法使用 null 标记将片段添加到堆栈,并使用参数null调用addToBackStack ,然后当前片段在提交时停止。 If the method is not called then the current fragment is destroyed and recreated when coming back.如果未调用该方法,则当前片段被销毁并在返回时重新创建。

getSupportFragmentManager().beginTransaction()
            .add(R.id.fragment_container,new BarFragment())
            .addToBackStack(null)
            .commit();

You can clearly find it in the documentation quote saying this:您可以在文档引用中清楚地找到它:

If you don't call addToBackStack() when you perform a transaction that removes a fragment, then that fragment is destroyed when the transaction is committed and the user cannot navigate back to it.如果您在执行删除片段的事务时不调用 addToBackStack(),则该片段在事务提交时被销毁,并且用户无法导航回它。 Whereas, if you do call addToBackStack() when removing a fragment, then the fragment is stopped and is later resumed if the user navigates back.然而,如果您在删除片段时确实调用了 addToBackStack(),那么片段会停止,然后如果用户导航回来,则会恢复。

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

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