为什么FragmentManager的BackStackEntry为0,即使我执行addToBackStack(null)

时间:2018-05-16 07:49:09

标签: android android-fragments

private BaseFragment fragment;
private FragmentManager fragmentManager;
private FragmentManager fragmentManager1;
private FragmentTransaction aFragmentTransaction;

这是我的OnCreate()方法中的代码:

fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction().replace(R.id.frame_container, 
fragment).commit();
fragmentTitle = getResources().getString(fragment.getFragmentTitle());
setTitle(fragmentTitle);

....还有一些代码...

aFragmentTransaction = fragmentManager.beginTransaction();
aFragmentTransaction.replace(R.id.frame_container, fragment);
aFragmentTransaction.addToBackStack(null);
aFragmentTransaction.commit();
setTitle(getResources().getString(fragment.getFragmentTitle()));

这是方法OnBackPressed()中相同活动的代码:

@Override
public void onBackPressed(){

fragmentManager1 = getSupportFragmentManager();
if (fragmentManager1.getBackStackEntryCount() > 0) {
    fragmentManager1.popBackStack();
} else {
    super.onBackPressed();
}

两者都属于同一个活动。 当我调试时,BackStack有0个元素。

编辑:执行aFragmentTransaction.addToBackStack(null)后,BackStack仍然为空

1 个答案:

答案 0 :(得分:0)

因为您更换了它而不是添加它。这样做:

aFragmentTransaction.add(R.id.frame_container, fragment);