前一个片段在安卓中使用返回栈返回到前一个片段时重新启动。

huangapple go评论85阅读模式
英文:

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 (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.

答案1

得分: 2

Welcome to Android Fragment Life !!

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();

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.

英文:

Welcome to Android Fragment Life !!

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();

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.

huangapple
  • 本文由 发表于 2020年7月28日 11:55:34
  • 转载请务必保留本文链接:https://go.coder-hub.com/63126785.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定