Krishnabhadra Krishnabhadra - 12 days ago 8
Android Question

Fragment onResume() & onPause() is not called on backstack

I have multiple fragment inside an activity. On a button click I am starting a new fragment, adding it to backstack. I naturally expected the

onPause()
method of current Fragment and
onResume()
of new Fragment to be called. Well it is not happening.

LoginFragment.java



public class LoginFragment extends Fragment{
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
final View view = inflater.inflate(R.layout.login_fragment, container, false);
final FragmentManager mFragmentmanager = getFragmentManager();

Button btnHome = (Button)view.findViewById(R.id.home_btn);
btnHome.setOnClickListener(new View.OnClickListener() {
public void onClick(View view){
HomeFragment fragment = new HomeFragment();
FragmentTransaction ft2 = mFragmentmanager.beginTransaction();
ft2.setCustomAnimations(R.anim.slide_right, R.anim.slide_out_left
, R.anim.slide_left, R.anim.slide_out_right);
ft2.replace(R.id.middle_fragment, fragment);
ft2.addToBackStack("");
ft2.commit();
}
});
}

@Override
public void onResume() {
Log.e("DEBUG", "onResume of LoginFragment");
super.onResume();
}

@Override
public void onPause() {
Log.e("DEBUG", "OnPause of loginFragment");
super.onPause();
}
}


HomeFragment.java



public class HomeFragment extends Fragment{
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
final View view = inflater.inflate(R.layout.login_fragment, container, false);
}

@Override
public void onResume() {
Log.e("DEBUG", "onResume of HomeFragment");
super.onResume();
}

@Override
public void onPause() {
Log.e("DEBUG", "OnPause of HomeFragment");
super.onPause();
}
}


What I expected, was,


  1. When button is clicked, LoginFragment gets replaced with
    HomeFragment,
    onPause()
    of LoginFragment, and
    onResume()
    of
    HomeFragment gets called

  2. When back is pressed, HomeFragment is poped out and LoginFragment is
    seen, and
    onPause()
    of HomeFragment and
    onResume()
    of LoginFragment
    gets called.



What I am getting is,


  1. When button is clicked, HomeFragment is correctly replacing
    LoginFragment, onResume() of HomeFragment is called, but onPause()
    of LoginFragment is never called.

  2. When back pressed, HomeFragment is correctly popping to reveal
    LoginFragment, onPause() of HomeFragment gets called, but onResume()
    of LoginFragment never gets called.



Is this the normal behaviour? Why is
onResume()
of LoginFragment not getting called when I press the back button.

Answer

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

Read the Handling the Fragment Lifecycle section of this article.