【问题标题】:ViewPager IllegalStateException with Fragments带有片段的 ViewPager IllegalStateException
【发布时间】:2014-07-22 15:29:12
【问题描述】:

在 Xamarin 中,我有一个 ViewPager 正在执行以下错误:

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

当我有三个Android.Support.V4.App.Fragments 并在它们之间滑动时会发生此错误。两个Android.Support.V4.App.Fragments 不会发生此错误。

这是我的Android.Support.V4.App.Fragment 代码:

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;
    }
}

这是我的ViewPagerAdapter 代码:

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];
    }
}

为什么会发生此错误,如何防止此错误发生?

提前致谢

编辑

这是我尝试过的代码:

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;

这是我得到的错误:

System.NullReferenceException:对象引用未设置为实例 一个对象

在这行代码处:

ViewGroup parent = (ViewGroup)View.Parent;

【问题讨论】:

    标签: android android-fragments android-viewpager xamarin illegalstateexception


    【解决方案1】:

    在你的 onCreateView() 方法中使用它,

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

    如果它已经有父视图,这将从其父视图中删除视图。

    【讨论】:

    • 查看我的编辑 ViewGroup parent = (ViewGroup) rootView.getParent();将视图更改为 rootView。
    猜你喜欢
    • 2016-11-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-06
    • 2016-10-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多