Fragment已经被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)

 

posted @ 2017-07-27 17:39  万物为铜  阅读(904)  评论(0编辑  收藏  举报