上下文:我有一个带片段的活动和3个InnerFragments.当调用Fragment onDestroy()时,我想从FragmentManager中删除内部片段. onDestroy()的代码如下.
问题:FragmentManager抛出NullPointerException,可能是在调用commitAllowingStateLoss()时.我不明白为什么.
@Override public void onDestroy() { super.onDestroy(); if (getFragmentManager().findFragmentById(R.id.fragment_framelayout_left) != null) { FragmentTransaction fragmentTransaction = getFragmentManager().beginTransaction(); fragmentTransaction.remove(mLeftFragment); fragmentTransaction.commitAllowingStateLoss(); } }
堆栈跟踪:
02-11 12:15:14.162: E/AndroidRuntime(25911): FATAL EXCEPTION: main 02-11 12:15:14.162: E/AndroidRuntime(25911): java.lang.NullPointerException 02-11 12:15:14.162: E/AndroidRuntime(25911): at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1419) 02-11 12:15:14.162: E/AndroidRuntime(25911): at android.support.v4.app.FragmentManagerImpl$1.run(FragmentManager.java:429) 02-11 12:15:14.162: E/AndroidRuntime(25911): at android.os.Handler.handleCallback(Handler.java:725) 02-11 12:15:14.162: E/AndroidRuntime(25911): at android.os.Handler.dispatchMessage(Handler.java:92) 02-11 12:15:14.162: E/AndroidRuntime(25911): at android.os.Looper.loop(Looper.java:137) 02-11 12:15:14.162: E/AndroidRuntime(25911): at android.app.ActivityThread.main(ActivityThread.java:5039) 02-11 12:15:14.162: E/AndroidRuntime(25911): at java.lang.reflect.Method.invokeNative(Native Method) 02-11 12:15:14.162: E/AndroidRuntime(25911): at java.lang.reflect.Method.invoke(Method.java:511) 02-11 12:15:14.162: E/AndroidRuntime(25911): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793) 02-11 12:15:14.162: E/AndroidRuntime(25911): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560) 02-11 12:15:14.162: E/AndroidRuntime(25911): at dalvik.system.NativeStart.main(Native Method)
解决方法
FragmentManager管理Activity级别的所有Fragment,它们的生命周期将与该父Activity绑定.子片段管理器管理片段级别的所有片段,它们的生命周期将与该父片段相关联.
因此,对于您的手机架构,使用getFragmentManager()将您的InnerFragment添加到您的Activity中.当Activity彻底销毁(通过后退按钮/完成())时,FragmentManager将为您销毁并释放InnerFragment.
对于您的平板电脑架构,使用getChildFragmentManager()(在最新的支持库中)将您的InnerFragments添加到Fragment.当Fragment彻底破坏时,FragmentManager会为你破坏和释放InnerFragments.
您不必自己管理释放和销毁碎片.我建议记录您的活动和碎片的生命周期事件,以便您可以观察它们的状态并确保正确的行为.