I move From Activity to FagmentA then FragmentA to FragmentB. When Press back Button while staying in FragmentB it goes to MainActivity(It should move to a Back fragment which is FragmentA). what's wrong with it?
Moving from Activity to FragmentA
Fragment fragment = new FragmentA() ;
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.setCustomAnimations(android.R.anim.fade_in,
android.R.anim.fade_out);
fragmentTransaction.replace(R.id.frame, fragment, CURRENT_TAG);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commitAllowingStateLoss();
Moving FramgentA to FragmentB
layout.removeAllViewsInLayout();
Fragment fragment =new FragmentB ;
FragmentManager fragmentManager = getActivity().getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.frame, fragment);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
Onbackpressed MainActivity
@Override
public void onBackPressed() {
android.app.FragmentManager fm = getFragmentManager();
if(fm.getBackStackEntryCount()>0){
fm.popBackStack();
}else{
super.onBackPressed();
}
Your problem is with your imports of FragmentManager
you use both :
android.support.v4.app.FragmentManager
and android.app.FragmentManager
change this :
@Override
public void onBackPressed() {
android.app.FragmentManager fm = getFragmentManager();
if(fm.getBackStackEntryCount()>0){
fm.popBackStack();
}else{
super.onBackPressed();
}
to:
@Override
public void onBackPressed() {
FragmentManager fm = getSupportFragmentManager();
if(fm.getBackStackEntryCount()>0){
fm.popBackStack();
}else{
super.onBackPressed();
}
You only add Fragment
s using the support FragmentManager
meaning your existing code will always return 0 here -> fm.getBackStackEntryCount()
until you use correct support FragmentManager
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.