使用ViewPager报错java.lang.IllegalStateException: The specified child already has a parent. You must ...

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

不知道你们在使用ViewPager的时候有没有碰到过这个问题, 反正我是碰到了,因此作个记录,但愿对之后有用ide

  从字面上看,就是说子view已经有了一个父控件,因此你得先把父控件remove掉.  由于每个子view 只能拥有一个父控件,可是当你滑动viewpager的时候,在PagerAdapter中的 instantiateItem 方法就会重复执行,这时候就会屡次添加父控件,因此若是不作处理,就会报这个错.code

    因此个人处理就是在用到public class MyPagerAdapter extends PagerAdapter 的时候,在他的instantiateItem方法中,先获取到父控件,判空下图片

@Override
	public Object instantiateItem(ViewGroup container, int position) {
		ImageView mImageView = new ImageView(context);
		// 设置图片根据imageView来将图片进行拉伸
		mImageView.setScaleType(ScaleType.FIT_XY);
		ViewGroup parent = (ViewGroup) mImageView.getParent();
		if (null != parent) {
			parent.removeAllViews();
		}
		// 当前页面为第几页(60000页) 而后除以集合的长度 取余数就是当前页面在list集合中对应图片的位置
		mImageView.setImageResource(list.get(position % list.size()).getIconId());
		container.addView(mImageView);
		return mImageView;
	}

 

而且在每个fragment的onCreateView中,都作了下面的处理ci

@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		if (null == view ) {
			view = inflater.inflate(R.layout.fragment5, container, false);
		} else {
			ViewGroup parent = (ViewGroup) view.getParent();
			if (null != parent) {
				parent.removeAllViews();
			}
		}
		
		 initView(view);
		 return view;
	}

 这样就不会报那个错了~~rem

相关文章
相关标签/搜索