8

I am having 4 (let's say 1,2,3 & 4) fragments. And at a time any one of them will be visible to User. In 2nd fragment I want to do something when user is coming on it. Now when User navigated to 3rd fragment & hits the back button, I want to run a some code. My problem is onResume is not getting called when user hits the back button & come to 2nd fragment.

hemu
  • 3,199
  • 3
  • 44
  • 66
  • Try to use `onAttach()` method, not `onResume()` – Procurares Mar 13 '13 at 12:34
  • Already tried....Actually OnAttch() is just called once when we attach it from fragment activity. – hemu Mar 13 '13 at 12:47
  • How are you switching between the fragments? Please add some example code. – antonyt Mar 16 '13 at 00:56
  • Are you replacing or adding the new fragment? Also be aware that according to the official documentation "fragment onResume() is generally tied to Activity.onResume of the containing Activity's lifecycle." – fasteque Sep 11 '13 at 15:25

2 Answers2

4

I recently bumped into the same problem, I know that its too late, but just in case some one else is looking for this, here's my answer:

Thanks @fasteque for narrowing down my search.

The fragments onResume() or onPause() will be called only when the Activities onResume() or onPause() is called. They are tightly coupled to the Activity.

But if you still want listen to the changes in your activity like which fragment is on top, and trigger events accordingly, you might wanna have a look at FragmentManager.OnBackStackChangedListener

Hope this helps :)

Ankit Popli
  • 2,809
  • 3
  • 37
  • 61
1

I've had the same problem. If you want to switch from 3rd fragment to 2nd fragment (with the back button or another way) you can call 2nd fragment in the onPause of 3rd fragment.

@Override
public void onPause() {
    super.onPause();

     Fragment2 fragment2= (Fragment2) getActivity().getSupportFragmentManager().findFragmentById(R.id.fragment2);
     if (fragment2!= null) {
         //you can call any function from fragment2
         fragment2.SomeFunctions();
     }
}
Okan Kocyigit
  • 13,203
  • 18
  • 70
  • 129
Geylani ARCA
  • 308
  • 1
  • 11