在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;
答案 0 :(得分:0)
在onCreateView()方法中使用它,
if (rootView != null) {
ViewGroup parent = (ViewGroup) rootView.getParent();//Updated
parent.removeView(rootView);
} else {
rootView = inflater.inflate(Resource.Layout.FragmentItem, container,
false);
}
如果该视图已经具有父视图,则会从其父视图中删除该视图。