在屏幕旋转时调用NavigationDrawer事件处理程序方法

时间:2014-06-03 04:35:57

标签: android android-fragments

我有一个带有NavigationDrawer的活动(不知道它是否重要)。单击NavigationDrawer上的项目时,会使用 newInstance()工厂方法将片段添加到主活动中。这个想法很简单。

程序运行时:

Inside MainActivity()

然后我点击NavigationDrawer上的一个项目:

Inside MyFragment.newInstance() // It is me who calls it.
Inside MyFragment() // This is called inside newInstance(). Nothing out of my expectation.

然后,我旋转屏幕:

Inside MainActivity() // FragmentManager re-creates the activity and the fragment for a new screen layout.
Inside MyFragment() // My saved data in Bundle persists.
Inside MyFragment.newInstance() // ???
Inside MyFragment() // Now that my saved data in Bundle object is lost, because it is no longer the old fragment.

这种奇怪行为的原因是什么?当我旋转屏幕时,谁负责调用newInstance()?

编辑:NavigationDrawer的代码默认由Android Studio生成。

// Helper component that ties the action bar to the navigation drawer.
private ActionBarDrawerToggle mDrawerToggle;

@Override
public void onConfigurationChanged(Configuration newConfig) {
    super.onConfigurationChanged(newConfig);
    // Forward the new configuration the drawer toggle component.
    mDrawerToggle.onConfigurationChanged(newConfig);
}

1 个答案:

答案 0 :(得分:1)

事实证明,Android Studio默认生成的代码是罪魁祸首。感谢Luksprog提出的建议和他的猜测天赋。 :d

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    // Read in the flag indicating whether or not the user has demonstrated awareness of the
    // drawer. See PREF_USER_LEARNED_DRAWER for details.
    SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(getActivity());
    mUserLearnedDrawer = sp.getBoolean(PREF_USER_LEARNED_DRAWER, false);

    if (savedInstanceState != null) {
        mCurrentSelectedPosition = savedInstanceState.getInt(STATE_SELECTED_POSITION);
        mFromSavedInstanceState = true;
    }

    // Select either the default item (0) or the last selected item.
    selectItem(mCurrentSelectedPosition);
}

问题的原因是 selectItem(mCurrentSelectedPosition); 行,每次创建NavigationDrawer时都会调用它,包括屏幕旋转的情况。