java.lang.IllegalStateException: Fragment already added: ******Effect 出現的原因是commit方法提交是非同步的,所以容易出現,判斷的時候是還沒有added的狀態,但是在真的添加的時候,重覆添加了,其實就是一個同步非同步的問題。 解決 ...
java.lang.IllegalStateException: Fragment already added: ******Effect
出現的原因是commit方法提交是非同步的,所以容易出現,判斷的時候是還沒有added的狀態,但是在真的添加的時候,重覆添加了,其實就是一個同步非同步的問題。
解決方式其實就是自己添加一個tag,每個fragment一個tag就可以解決重覆添加導致的異常了。
mAdded = new boolean[]{false, false, false, false, false, false};
private synchronized void setIndexSelected(int index) { Logcat.d(TAG, "mIndex " + mIndex + "; index " + index); if(mIndex == index){ return; } FragmentManager fragmentManager = getSupportFragmentManager(); FragmentTransaction ft = fragmentManager.beginTransaction(); //隱藏 ft.hide(mFragments[mIndex]); //判斷是否添加 if (index < mFragments.length) { if (!mFragments[index].isAdded() && !mAdded[index]) { Logcat.d(TAG, "add " + mFragments[index]); ft.add(R.id.content, mFragments[index]).show(mFragments[index]); mAdded[index] = true; } else { Logcat.d(TAG, "show " + mFragments[index]); ft.show(mFragments[index]); } } ft.commit(); //再次賦值 mIndex = index; }
[2017/7/21 10:42:08] 07-21 05:41:00.457 4835 4835 E AndroidRuntime: java.lang.IllegalStateException: Fragment already added: SoundEffectFragment{acd69f9 #1 id=0x7f0e0205} [2017/7/21 10:42:08] 07-21 05:41:00.457 4835 4835 E AndroidRuntime: at android.support.v4.app.FragmentManagerImpl.addFragment(FragmentManager.java:1323) [2017/7/21 10:42:08] 07-21 05:41:00.457 4835 4835 E AndroidRuntime: at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:675) [2017/7/21 10:42:08] 07-21 05:41:00.457 4835 4835 E AndroidRuntime: at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1617) [2017/7/21 10:42:08] 07-21 05:41:00.457 4835 4835 E AndroidRuntime: at android.support.v4.app.FragmentManagerImpl$1.run(FragmentManager.java:517) [2017/7/21 10:42:08] 07-21 05:41:00.457 4835 4835 E AndroidRuntime: at android.os.Handler.handleCallback(Handler.java:739) [2017/7/21 10:42:08] 07-21 05:41:00.457 4835 4835 E AndroidRuntime: at android.os.Handler.dispatchMessage(Handler.java:95) [2017/7/21 10:42:08] 07-21 05:41:00.457 4835 4835 E AndroidRuntime: at android.os.Looper.loop(Looper.java:148) [2017/7/21 10:42:08] 07-21 05:41:00.457 4835 4835 E AndroidRuntime: at android.app.ActivityThread.main(ActivityThread.java:5417) [2017/7/21 10:42:08] 07-21 05:41:00.457 4835 4835 E AndroidRuntime: at java.lang.reflect.Method.invoke(Native Method) [2017/7/21 10:42:08] 07-21 05:41:00.457 4835 4835 E AndroidRuntime: at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:742) [2017/7/21 10:42:08] 07-21 05:41:00.457 4835 4835 E AndroidRuntime: at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:632)