Android 在屏幕旋转时调用NavigationDrawer事件处理程序方法
我有一个NavigationDrawer的活动(不知道它是否重要)。单击NavigationDrawer上的项目时,将使用newInstance()factory方法向主活动添加一个片段。想法就这么简单 程序运行时:Android 在屏幕旋转时调用NavigationDrawer事件处理程序方法,android,android-fragments,Android,Android Fragments,我有一个NavigationDrawer的活动(不知道它是否重要)。单击NavigationDrawer上的项目时,将使用newInstance()factory方法向主活动添加一个片段。想法就这么简单 程序运行时: Inside MainActivity() 然后单击NavigationDrawer上的一个项目: Inside MyFragment.newInstance() // It is me who calls it. Inside MyFragment() // This is c
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);
}
原来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时都会调用它,包括屏幕旋转的情况。请查看您的onConfigurationChanged方法……我尚未实现它。它仍然是从Activity继承的默认值。如果没有代码,我们只能猜测。这种奇怪行为的原因是什么最有可能的情况是,您没有考虑配置更改,而是从导航抽屉中再次调用侦听器。几乎所有的代码都是默认生成的,所以我懒得在这里复制粘贴它们。您是对的——在旋转屏幕时调用了onNavigationDrawerItemSelected(int)。有什么建议可以防止这种情况吗?如果该调用发生在
onCreate
回调中,则检查传入的捆绑包是否为null
。如果它不是null,那么您正在处理配置更改,在这种情况下,您不需要再次调用该方法。