Reputation: 1861
I need to execute some code whenever a fragment is displayed to the user.
Looking through the API the closest hook method I could see for this is onResume. However, from debugging through my code it seems that onResume is not called when the user selects the back-button to return to a previously displayed fragment.
Just to clarify the behaviour I am seeing:
I have a 'parent' activity which configures tabs in an ActionBar... and 2 fragments F1 and F2.
The user selects a tab and F1 is loaded into the activity. On a button press, the user can navigate to F2. This is not a separate tab... F2 is swapped into the layout.
Adding log statements, I can see that when the user selects the back-button on F2, the following happens....
1) onPause() is called on F2. 2) F1 is loaded into the activity... but onResume() on F1 is not called
There are no errors in the logs at this time.
Any ideas what I'm doing wrong here?
Thanks in advance,
Neil.
Upvotes: 6
Views: 12587
Reputation: 75629
This bit odd question, because any existing class method is guaranteed to be called when event that this certain method was designed to be called for occurs and all the conditions are met. Choose any that fits task you want to accomplish best. See docs here
Upvotes: 0
Reputation: 1861
Ok, it seems this one was pilot-error. My original code to switch between fragments in an activity was....
public void switchFragment(Fragment newFragment, String tag) {
getSupportFragmentManager()
.beginTransaction()
.add(android.R.id.content, newFragment)
.addToBackStack(tag)
.commit();
}
The call to add() in the above code should actually be to replace(). It seems that not replacing the fragment in the activity messes with the back-button behaviour.
Have to be honest and admit I'm not 100% sure exactly why this happens. However, after making the change, the onResume() method is called on the destination fragment, once the back-button is called.
Upvotes: 10