我必須使用Android Fragment創建項目。我得到以下異常,當我嘗試顯示片段第二次:第二次佈局充氣時,Android片段引發了我的異常
java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first.
我發現很多話題對此非常明確的例外,但我沒有發現我的項目的解決方案。這是我的片段代碼:
public class MyFragement extends Fragment {
private View view;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
if (view == null) {
view = inflater.inflate(R.layout.mylayout, container, false);
} else {
ViewGroup parent = (ViewGroup) view.getParent();
if (parent != null) {
parent.removeView(view);
}
}
return view;
}
@Override
public void onDestroyView() {
super.onDestroyView();
if (view != null) {
ViewGroup parentViewGroup = (ViewGroup) view.getParent();
if (parentViewGroup != null) {
parentViewGroup.removeView(view);
}
}
}
....
}
線
view = inflater.inflate(R.layout.mylayout, container, false);
拋出,當它第二次執行的例外。正如例外情況所示,我在視圖被銷燬時將視圖移除到父視圖中,但它不能解決問題。
XML文件(佈局/ mylayout.xml):
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#FBF3E7"
android:padding="5dp" >
<ListView
android:id="@+id/menu_item_listview"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:choiceMode="none" >
</ListView>
</LinearLayout>
是任何人有一個想法來解決這個問題?
在你的代碼,我不看行'視圖= inflater.inflate(getLayout(),集裝箱,FALSE);'。只有用R.id.mylayout調用inflate()。你準確地使用了哪一個? –
爲什麼你使用'R.id.'而不是'R.layout'?我認爲'R.id.mylayout' alredy存在於父視圖中,並且您的片段嘗試添加一個'R.id.mylayout'視圖。 – fisher3421