Android onBackStackChanged() not called

2019-04-04 07:42发布

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.

2条回答
贪生不怕死
2楼-- · 2019-04-04 08:25

the only thing needed is to do this onCreate:

getFragmentManager().addOnBackStackChangedListener(this);
查看更多
Juvenile、少年°
3楼-- · 2019-04-04 08:34

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();
}
查看更多
登录 后发表回答