英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论