Search code examples
androidandroid-fragmentsandroid-viewpagerxamarinillegalstateexception

ViewPager IllegalStateException with Fragments


In Xamarin, I have a ViewPager that is performing the following error:

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

This error occurs when I have three Android.Support.V4.App.Fragments and I swipe between them. This error does not happen with two Android.Support.V4.App.Fragments.

Here is my Android.Support.V4.App.Fragment code:

public class FragmentItem : Android.Support.V4.App.Fragment
{
    View rootView;
    TextView textView;

    public override View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        if (rootView == null) 
        {
            rootView = inflater.Inflate(Resource.Layout.FragmentItem, container,false);
            textView = rootView.FindViewById<TextView>(Resource.Id.textViewDisplay);
        }

        return rootView;
    }
}

Here is my ViewPagerAdapter code:

public class ViewPagerAdapter : FragmentPagerAdapter {

    private List<Android.Support.V4.App.Fragment> fragments;
    int fragmentCount;

    public ViewPagerAdapter(Android.Support.V4.App.FragmentManager fm, List<Android.Support.V4.App.Fragment> fragments) : base(fm)
    {
        this.fragments = fragments;
        fragmentCount = fragments.Count;
    }

    public override int Count 
    {
        get 
        {
            return fragmentCount;   
        }   
    }

    public override Android.Support.V4.App.Fragment GetItem (int position)
    {
        return fragments[position];
    }
}

Why is this error happening and how can I prevent this error from happening?

Thanks in advance

EDIT

Here is the code that I have tried:

if (rootView != null) 
{
    ViewGroup parent = (ViewGroup)View.Parent;
    parent.RemoveView(rootView);
} else {
    rootView = inflater.Inflate(Resource.Layout.FragmentItem, container, false);
    textView = rootView.FindViewById<TextView>(Resource.Id.textViewDisplay);            
}
return rootView;

Here is the error that I am getting:

System.NullReferenceException: Object reference not set to an instance of an object

At this line of code:

ViewGroup parent = (ViewGroup)View.Parent;

Solution

  • Use this in your onCreateView() method,

     if (rootView != null) {
            ViewGroup parent = (ViewGroup) rootView.getParent();//Updated
            parent.removeView(rootView);
        } else {
            rootView = inflater.inflate(Resource.Layout.FragmentItem, container,
                    false);
        }
    

    this will remove the view from its parent view if this already has parent view.