当布局第二次膨胀时,Android片段会引发异常

时间:2013-10-30 10:04:36

标签: android android-layout android-fragments

我必须使用Android Fragment创建一个项目。当我尝试第二次显示片段时,我得到以下异常:

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文件(layout / 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>

有人有想法解决这个问题吗?

1 个答案:

答案 0 :(得分:0)

试试这个......

public class MyFragement extends Fragment {

private View view;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
    view = inflater.inflate(R.id.mylayout, container, false);   
    return view;
}

@Override
public void onDestroyView() {
    super.onDestroyView();
}
....

}