简体   繁体   中英

How did I stop IllegalStateExceptions from being thrown with LayoutInflater().inflate(int resource, ViewGroup root, boolean attachToRoot)?

I recently recently ran into an issue while setting up a viewpager with 3 fragments. When the application ran it crashed with a

java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first

Here is the code for creating list list of fragments to pass to the pageAdapter.

private Vector<Fragment> getFragments() {
    Vector<Fragment> list = new Vector<Fragment>();

    list.add(new Fragment1());
    list.add(new Fragment2());
    list.add(new Fragment3());

    return list;

Each of the fragments were essentially the same except for a being created with different layouts. Here was the original code I had for one of the fragments. public class Fragment1 extends Fragment {

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
    View v = getActivity().getLayoutInflater().inflate(R.layout.fragment1, container);
    return v;
}
} 

But when I ran it like this it kept crashing with the IllegalStateException. I found that the issue was coming from the fragments being created. After some Googling I tried changing the code for the fragment to this.

public class Fragment1 extends Fragment {

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
    View v = getActivity().getLayoutInflater().inflate(R.layout.fragment1, container, false);

    return v;
}
}

This resolved the issue and I no longer got the IllegalStateException except I have no idea how this worked. What exactly does this boolean do? And what does this exception mean? I had tried adding the method call like it suggusted but that did not resolve it. Also I tried changing this boolean to true and I got the same error again. The android docs say its attachToRoot but isn't that what I want to do? Attach my 3 fragments to the rootview, which is the viewpager? If anyone could explain this it would be greatly appreciated.

The boolean parameter of the 3-arg version of LayoutInflater.inflate() determines whether the LayoutInflater will add the inflated view to the specified container. For fragments, you should specify false because the Fragment itself will add the returned View to the container. If you pass true or use the 2-arg method, the LayoutInflater will add the view to the container, then the Fragment will try to do so again later, which results in the IllegalStateException .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM