问题
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