Android onBackStackChanged() not called
Asked Answered
P

2

14

I have an Activity like the code below:

public class AuthenticatedMainActivity extends Activity implements FragmentManager.OnBackStackChangedListener{

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        .............
        FragmentManager fragmentManager = getFragmentManager();           
        fragmentManager.beginTransaction().add(R.id.frame_container,fragment, "First").addToBackStack(null).commit();
    }

    private void switchFragment(Fragment fragment){            
      FragmentManager fragmentManager = getFragmentManager();
      fragmentManager.beginTransaction()
        .replace(R.id.frame_container, fragment).addToBackStack("Tag").commit();
    }

    @Override
public void onBackStackChanged() {
    System.out.println("====================================================changeeeeeeeeeeeeeeeeeeeeeeeeee");
}       
}

But the onBackStackChanged() method is never called even After successfully replaced fragments with the switchFragment method.

Psychographer answered 12/5, 2014 at 0:45 Comment(0)
A
30

You need to add your Activity as a OnBackStackChangedListener using addOnBackStackChangedListener.

Example:

@Override
protected void onCreate(Bundle savedInstanceState) {
    .............
    FragmentManager fragmentManager = getFragmentManager();     
    fragmentManager.addOnBackStackChangedListener(this);      
    fragmentManager.beginTransaction().add(R.id.frame_container,fragment, "First").addToBackStack(null).commit();
}
Alexia answered 12/5, 2014 at 1:55 Comment(2)
Turns out you have to explicitly call: .addToBackStack(null) otherwise onBackStackChanged is not called even when correctly registered!Pariah
@BenMartenThat's because fragment transactions are not added to backstack by default.Again
S
0

the only thing needed is to do this onCreate:

getFragmentManager().addOnBackStackChangedListener(this);
Sammysamoan answered 7/12, 2015 at 21:28 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.