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

瘦欲@ 提交于 2021-01-29 10:09:15

问题


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:


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.



来源:https://stackoverflow.com/questions/63126785/previous-fragment-is-restarting-when-we-go-back-to-previous-fragment-using-backs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!