我正在尝试操作片段删除/添加/替换,当我尝试删除并再次添加相同的片段类(不是相同的实例)时,问题就开始了。
我清除了整个活动:
for (int i = 0; i < frags.length; i++) {
BaseFragment fragment = frags[i];
if (!exsitingFragments.contains(fragment))
continue;
FragmentTransaction ft1 = getSupportFragmentManager().beginTransaction();
ft1.detach(fragment);
ft1.remove(fragment);
ft1.commit();
getSupportFragmentManager().executePendingTransactions();
}
并添加片段的新实例:
for (Object object : fragmentTypes) {
FragmentTransaction ft2 = getSupportFragmentManager().beginTransaction();
Class<? extends BaseFragment> fragmentType = (Class<? extends BaseFragment>) object;
Fragment finalFragment = Tools.createNewInstance(fragmentType);
ft2.add(parentViewId, finalFragment);
ft2.commit();
getSupportFragmentManager().executePendingTransactions();
}
这第一次效果很好,也适用于应用程序中的所有其他屏幕,但是,当我尝试重新创建屏幕时,例如再次调用此逻辑,删除所有片段,并添加这些片段的新实例,我得到以下错误:
08-14 15:20:50.086: E/AndroidRuntime(11443): java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first.
08-14 15:20:50.086: E/AndroidRuntime(11443): at android.view.ViewGroup.addViewInner(ViewGroup.java:3739)
08-14 15:20:50.086: E/AndroidRuntime(11443): at android.view.ViewGroup.addView(ViewGroup.java:3610)
08-14 15:20:50.086: E/AndroidRuntime(11443): at android.view.ViewGroup.addView(ViewGroup.java:3586)
08-14 15:20:50.086: E/AndroidRuntime(11443): at android.view.LayoutInflater.rInflate(LayoutInflater.java:770)
08-14 15:20:50.086: E/AndroidRuntime(11443): at android.view.LayoutInflater.inflate(LayoutInflater.java:498)
08-14 15:20:50.086: E/AndroidRuntime(11443): at android.view.LayoutInflater.inflate(LayoutInflater.java:398)
08-14 15:20:50.086: E/AndroidRuntime(11443): at com.mypermissions.core.ui.BaseFragment.onCreateView(BaseFragment.java:83)
08-14 15:20:50.086: E/AndroidRuntime(11443): at android.support.v4.app.Fragment.performCreateView(Fragment.java:1500)
08-14 15:20:50.086: E/AndroidRuntime(11443): at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:927)
08-14 15:20:50.086: E/AndroidRuntime(11443): at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1104)
08-14 15:20:50.086: E/AndroidRuntime(11443): at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:682)
08-14 15:20:50.086: E/AndroidRuntime(11443): at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1467)
08-14 15:20:50.086: E/AndroidRuntime(11443): at android.support.v4.app.FragmentManagerImpl.executePendingTransactions(FragmentManager.java:472)
现在这很奇怪,因为它只在片段中有 ViewPager 视图时发生,在所有其他情况下,到目前为止这个逻辑工作正常,奇怪的是抛出这个错误是因为NoSaveStateFrameLayout已经有一个父视图,而不是任何其他视图...
我试过这个:
ViewGroup rootView = (ViewGroup) getWindow().getDecorView().findViewById(android.R.id.content);
rootView.removeAllViews();
但是经过短暂的调试后,我发现有多个NoSaveStateFrameLayout实例,并且我可以删除的实例与导致异常的实例不同。
知道如何解决吗?