当我们使用android中的backstack返回上一个片段时,上一个片段正在重新启动 [英] Previous fragment is restarting when we go back to previous fragment using backstack in android

查看:83
本文介绍了当我们使用android中的backstack返回上一个片段时,上一个片段正在重新启动的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

让我们说我们有两个片段,而我们在第二个片段中,那么如果有人按下后退按钮,那么我们将使用backstack成功返回上一个片段(即第一个片段),但是问题在于,上一个片段正在重新启动所有内容.我想在不按任何重新启动或初始化的情况下显示上一个片段的内容.在此先感谢您.

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 (i.e. first fragment) using backstack but the problem is that the previous fragment is restarting everything. I want to display content of previous fragment without any restarting or initializing when we press back button.Thanks in advance.

推荐答案

欢迎使用Android Fragment Life !!

Welcome to Android Fragment Life !!

如@Uuu Uuu所建议,添加片段时需要使用add()方法.您正在重叠片段,因为每次都会添加一个新片段.

As suggested by @Uuu Uuu, you need to use add() method while adding fragment. 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();

如果您不熟悉android开发,请了解片段/活动生命周期,其中有一篇很棒的文章

If you are new to android development, please learn about the fragment/activity life cycle, there is a wonderful article By Jose Alcérreca

我希望这会有所帮助,祝您编程愉快.

I hope this will help, happy coding.

这篇关于当我们使用android中的backstack返回上一个片段时,上一个片段正在重新启动的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆