在调用popbackstack()后,所有添加的片段都显示出来,为什么?

时间:2016-08-19 07:50:15

标签: android android-fragments fragment android-lifecycle

我在MainActivity中有3个片段A,B,C。

A,B,C扩展了BaseFragment:

class BaseFragment extents Fragment{
  public void onHiddenChanged(boolean hidden) {
    super.onHiddenChanged(hidden);
    Log.d("onHiddenChanged:",this.getClass().getName()+" hidden:"+hidden);    
    }
    ...
}

和MainActiviy那样:

class MainActiviy extents Activity{
   onCreate(){
     ...
     fragmentTransaction.add(android.R.id.content, fragmentA, fragmentA.getClass().getName());
     fragmentTransaction.addToBackStack(fragmentA.getClass().getName());
     fragmentTransaction.commit();

     ...

  }
}

单击fragmentA时,只需输入fragmentB(只需添加B并隐藏A,然后将B添加到BackStack):

fragmentTransaction.add(android.R.id.content, fragmentB, fragmentB.getClass().getName());
fragmentTransaction.addToBackStack(fragmentB.getClass().getName());
fragmentTransaction.hide(fragmentA).commit();

单击fragmentB时,只需输入fragmentC,就像上面一样。

所以,我输入A,输入B,逐步输入C,然后在FragmentC中按下后退按钮, 我注意到,所有添加的片段都显示出来了:

onHiddenChanged:FragmentB
onHiddenChanged:FragmentA

这不是我的期望。当我在FragnmentC中按BackButton时,我只想显示FragmentB,并且片段A保持隐藏状态。

1 个答案:

答案 0 :(得分:0)

因为您添加所有片段而不是替换。

我建议您使用此方法,而不是添加新片段并隐藏旧片段。

private void changeFragment(Fragment frag, boolean saveInBackstack) {
    String backStateName = ((Object) frag).getClass().getName();

    try {
        FragmentManager manager = getSupportFragmentManager();

        if (manager.findFragmentByTag(backStateName) == null) {
            //fragment not in back stack, create it.
            FragmentTransaction transaction = manager.beginTransaction();
            transaction.replace(R.id.container, frag, backStateName);

            if (saveInBackstack) {
                Log.d(TAG, "Change Fragment: addToBackTack " + backStateName);
                transaction.addToBackStack(backStateName);
            } else {
                Log.d(TAG, "Change Fragment: NO addToBackTack");
            }

            transaction.commit();
        } else {
            manager.popBackStack();
        }
    } catch (IllegalStateException exception) {
        Log.w(TAG, "Unable to commit fragment, could be activity as been killed in
    }
}