先前片段的onSaveInstanceState被称为当前片段的on-orientation

时间:2014-07-21 05:48:48

标签: android android-fragments

我在做什么 ::

  • 我将一个片段(eg:: Fragment-A)加载到容器中 onSaveInstanceState事件我将一些数据存储到包

我使用代码

@Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);

        outState.putInt("yourSpinner", spnSearchByCity.getSelectedItemPosition());

    }
  • 现在我replace container点击按钮Fragment-BFragment-A

我使用代码

fragment = FrgMdMap.newInstance(messengerObj);

                    if (fragment != null) {
                        getFragmentManager().beginTransaction().replace(R.id.content_frame, fragment).addToBackStack(null).commit();
                    }
  • 我已成功加载Fragment-B

  • 现在关于Fragment-B的方向更改onSaveInstanceState Fragment-A id


问题 ::

  • 这是怎么回事?
  • 我怎样才能确保不会发生这种情况?

1 个答案:

答案 0 :(得分:2)

How is this taking place ?

实际上Fragment-A仍然存在且位于您Fragment-B下面,因为您更换了片段后添加了addToBackStack(null)

How can i make sure this wont happen ?

您可以删除addToBackStack(null)或计算onSaveInstanceState方法中已堆叠片段的数量,当它为0时,您可以在onSaveInstanceState

中运行代码

修改

public void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);
    FragmentManager fm = getActivity().getSupportFragmentManager();
    if(fm.getBackStackEntryCount() == 0)
    outState.putInt("yourSpinner", spnSearchByCity.getSelectedItemPosition());

}