简体   繁体   English

当我们 go 使用 android 中的 backstack 回到上一个片段时,上一个片段正在重新启动

[英]Previous fragment is restarting when we go back to previous fragment using backstack in android

lets say we have two fragment and we are in second fragment then if someone press back button then we successfully go back to the previous fragment (ie first fragment) using backstack but the problem is that the previous fragment is restarting everything.假设我们有两个片段,我们在第二个片段中,然后如果有人按下后退按钮,那么我们成功 go 使用 backstack 返回到前一个片段(即第一个片段),但问题是前一个片段正在重新启动一切。 I want to display content of previous fragment without any restarting or initializing when we press back button.Thanks in advance.当我们按下后退按钮时,我想显示前一个片段的内容而不需要任何重新启动或初始化。提前致谢。

Welcome to Android Fragment Life !!欢迎来到 Android 碎片生活!!

As suggested by @Uuu Uuu, you need to use add() method while adding fragment.正如@Uuu Uuu 所建议的,您需要在添加片段时使用 add() 方法。 You are getting the fragment overlapped because there is a new fragment added each time.您正在使片段重叠,因为每次都会添加一个新片段。

You simply need to do a check if the fragment exits already then there is no need to add a new fragment.您只需要检查片段是否已经存在,则无需添加新片段。 You can assign a 'tag' when adding fragment.您可以在添加片段时分配一个“标签”。 Code as follows-代码如下——

if (fragmentManager.findFragmentByTag("First Fragment") == null)
         fragmentManager.beginTransaction().add(R.id.fragment, new FirstFragment(), "First Fragment").commit();

If you are new to android development, please learn about the fragment/activity life cycle, there is a wonderful article By Jose Alcérreca如果您是 android 开发新手,请了解片段/活动生命周期,有一篇精彩的文章作者 Jose Alcérreca

I hope this will help, happy coding.我希望这会有所帮助,快乐的编码。

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

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