我正在尝试使用 FragmentTransition 将新片段添加到空 FrameLayout 并且我不断收到以下异常:
java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first.
at android.view.ViewGroup.addViewInner(ViewGroup.java:2840)
at android.view.ViewGroup.addView(ViewGroup.java:2735)
at android.view.ViewGroup.addView(ViewGroup.java:2691)
at android.view.ViewGroup.addView(ViewGroup.java:2671)
at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:739)
at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:919)
at android.app.BackStackRecord.run(BackStackRecord.java:578)
at android.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1217)
at android.app.FragmentManagerImpl.executePendingTransactions(FragmentManager.java:384)
at android.someApp.OverviewListFragment.showDetailsForSelectedMessage(OverviewListFragment.java:67)
调试时,我注意到 FrameLayout 试图将自己添加为自己的孩子,这似乎导致了这个异常。
这是我尝试将片段添加到的活动的 layout.xml 文件:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="match_parent">
<fragment
android:name="android.someApp.OverviewListFragment"
android:id="@+id/overview_list_fragment"
android:layout_weight="0.3"
android:layout_width="0px"
android:layout_height="match_parent" />
<FrameLayout
android:id="@+id/scenario_details_container"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:background="?android:attr/detailsElementBackground"/>
</LinearLayout>
这是我尝试执行转换的地方:
private void showDetailsForSelectedMessage() {
ScenarioDetailsFragment fragment = ScenarioDetailsFragment.newInstance(selectedMessage);
getFragmentManager().beginTransaction()
.replace(R.id.scenario_details_container, fragment)
.disallowAddToBackStack() //Problem occurs with and without this line
.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE)
.commit();
getFragmentManager().executePendingTransactions();
}
我已经为这个问题苦苦挣扎了太久了。有没有人知道这里发生了什么?