在使用ViewPager的时候遇到一个错误java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first.。经过多次调试及网上查找相关资料,终于弄明白是咋回事,现记录如下:

首先跟大家讲解一下为何会出现该错误,然后再提供自己的错误代码分析错误原因及解决方案。

一为何会报java.lang.IllegalStateException: The specified child already has a parent.错误

根据The specified child already has a parent. You must call removeView() on the child's parent first.的字面意思是一个子View已经存在一个父View,你必须先调用该子视图的父视图的 removeView() 方法,这种情况通常出现在动态添加视图的情况下,出现这种错误的原因是一个子控件只允许存在一个父控件,而很多时候在动态添加视图的时候,我们不知道该子视图是否已存在父视图,当已存在的时候就会报错。

二错误代码分析错误及解决方案:

出错的代码主要是在ViewPager的适配器类的instantiateItem方法中,因为在该方法中我们通常会动态的添加视图。在自己的项目的主界面中定义了一个ViewPager用来循环显示多个GridView,而在主界面中GridView是通过LayoutInflater来动态获取的,代码如下:

                LayoutInflater inflater=getActivity().getLayoutInflater();
View view=inflater.inflate(R.layout.viewpager,null);
campanyGridView=(GridView) view.findViewById(R.id.campany_gridview_1);

然后将多个campanyGridView添加到List集合中,然后将该ArrayList集合对象作为参数传递给ViewPager对应的Adapter,代码如下:

public class ViewPaperAdapter extends PagerAdapter {

	private ArrayList<View> viewList;

	public ViewPaperAdapter(ArrayList<View> viewList) {
// TODO Auto-generated constructor stub
this.viewList=viewList;
}
@Override
public void destroyItem(ViewGroup container, int position, Object object) {
// TODO Auto-generated method stub
//super.destroyItem(container, position, object);
container.removeView(viewList.get(position));
} @Override
public Object instantiateItem(ViewGroup container, int position) { container.addView(viewList.get(position));
return viewList.get(position);
} @Override
public int getCount() {
// TODO Auto-generated method stub
return viewList.size();
} @Override
public boolean isViewFromObject(View arg0, Object arg1) {
// TODO Auto-generated method stub
return arg0==arg1;
} }

其中PagerAdapter中的instantiateItem方法是用来显示我们添加的视图控件的,其中视图对应的R.layout.viewpager的XML文件如下:

<?xml version="1.0" encoding="utf-8"?>

  <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<GridView
android:id="@+id/campany_gridview_1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:horizontalSpacing="10dp"
android:verticalSpacing="10dp"
android:numColumns="3" ></GridView> </LinearLayout>

布局很简单,只是在LinearLayout中放了一个GridView控件而已。但是当点击自己项目APP的底部导航按钮(界面类似QQ)来切换界面时报错,即java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first.。通过我们上述讲解大家应该能够明白为何出错。

错误分析:因为ViewPager的视图的显示是在PagerAdapter中通过instantiateItem方法来动态添加的,通常我们在该方法中会调用container.addView(viewList.get(position));来添加一个视图,即调用ViewGroup的addView来动态添加控件,但是可以看到在我们的R.layout.viewpager的XML文件中GridView的外部是LinearLayout布局控件,即此时GridView的父控件为LinearLayout,这样就相当于把一个以存在父控件的子控件动态的添加到一个ViewGroup容器中,这是不被允许的,因为一个子控件只允许存在一个父容器控件,因此会报错。

解决方案:通过上述的分析可以很容易找到解决方案:

1去除R.layout.viewpager的XML文件中GridView的外部的LinearLayout布局控件,这样GridView就不存在父容器控件。

2在在PagerAdapter中通过instantiateItem方法中动态添加视图前做一个简单的判断,判断待添加的视图是否已存在父控件,若存在则调用removeAllViews()去除之。代码如下:

public Object instantiateItem(ViewGroup container, int position) {
// TODO Auto-generated method stub
View v=viewList.get(position);
ViewGroup parent = (ViewGroup) v.getParent();
//Log.i("ViewPaperAdapter", parent.toString());
if (parent != null) {
parent.removeAllViews();
}
container.addView(viewList.get(position));
return viewList.get(position);
}

可以看到第一种方案简单粗暴,但适用性不强,因为我们要添加的一个视图可能很复杂,而不是一个简单的GridView,那么我们必须使用类似LinearLayout的基本布局控件来控制我们的视图,因此第二种方案很显然适用此种情况。

三总结:

ViewGroup的addView()方法不能添加一个已存在父控件的视图,因此在使用类似ViewPager的控件动态添加视图时,要在addView前先判断再添加,上述案例可以扩展为不能使用addView()对同一个控件动态添加两次,因为第一个添加时已表示该子控件已存在父容器控件,第二次添加时尽管其父容器控件是同一个控件,但是相当于该子视图已存在父容器控件,因此仍会报错,如下代码是错误的:

private void initView() {
LinearLayout viewGroup = (LinearLayout) findViewById(R.id.main_activity_linearlayout);
LayoutInflater inflater = LayoutInflater.from(this);
View textView = inflater.inflate(R.layout.test, null);
viewGroup.addView(textView);
viewGroup.addView(textView); //这个地方出错,不能对其添加两次。
}

解决方案也很简单,对于添加的第二个视图,重新用一个布局文件定义,然后通过inflater.inflate获取再动态添加。

安卓java.lang.IllegalStateException: The specified child already has a parent.解决方案的更多相关文章

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

    在ViewPager中,用Fragment显示页面时,报错: java.lang.IllegalStateException: The specified child already has a pa ...

  2. java.lang.IllegalStateException: The specified child already has a parent. You must call removeView

     java.lang.IllegalStateException: The specified child already has a parent. You must call removeVi ...

  3. 关于viewpager 里嵌套 listview 同时实现翻页功能的“java.lang.IllegalStateException: The specified child..."异常处理

    这几天做项目用到了ViewPager,因为它可以实现左右划动多个页面的效果,然后 再每个页面里使用ListView,运行时总是出现”PagerAdapter java.lang.IllegalStat ...

  4. SpringMVC Tomcat 启动时报错:java.lang.IllegalStateException: Error starting child

    大概原因如下: 1.Controller里RequestMapping("/test")前面没有"/"; 2.jar包冲突,比如我的将数据库连接版本由5.1.6 ...

  5. 异常java.lang.IllegalStateException的解决

    在初始化viewPagerAdapter时,显示异常.从网上找了找有两类这样的问题,一种是说给一个视图设置了两个父类,如: TextView tv = new TextView();layout.ad ...

  6. Android IllegalStateException: The specified child already has a parent问题解决办法

    最近遇到一个很让人头疼的问题,使用viewpager动态添加页面或者删除页面时出现了问题(java.lang.IllegalStateException: The specified child al ...

  7. Tomcat部署项目时出错java.lang.IllegalStateException: ContainerBase.addChild: start:org.apache.catalina.Life

    Tomcat部署项目时出错java.lang.IllegalStateException: ContainerBase.addChild: start:org.apache.catalina.Life ...

  8. myeclipse 无法启动 java.lang.IllegalStateException: Unable to acquire application service. Ensure that the org.eclipse.core.runtime bundle is resolved and started (see config.ini).

    把myeclipse10 按照目录完整拷贝到了另外一台电脑, 另外的目录 原安装目录 D\:\soft\i\myeclipse10 新安装目录 E\:\soft\myeclipse10 双击启动失败, ...

  9. java.lang.IllegalStateException:Couldn't read row 0, col -1 from CursorWindow. Make sure the Cursor is initialized correctly before accessing data from it.

    java.lang.RuntimeException: Unable to start activity ComponentInfo{com.xxx...}: java.lang.IllegalSta ...

随机推荐

  1. hdu 5476 (计算几何)

    题意:求三角形内∠MPB+∠APC=∠MPC+∠APB的轨迹长度- - 1.基于M的中垂线       2.三角形内的圆弧(比赛只有看自己能否猜中),ps.以下是别人家的证明 #include < ...

  2. centos下 apache+mysql+php的安装

    一.安装 MySQL 首先来进行 MySQL 的安装.打开超级终端,输入: [root@localhost ~]# yum install mysql mysql-server 安装完毕,让 MySQ ...

  3. Database Design Guidelines

    Database Design Guidelines Principles Support popular databases Name Style Table Name Style: Pascal ...

  4. select动态绑定vue.js

    <select v-model="selected"> <option v-for="option in options" v-bind:va ...

  5. 安装插件出现eclipse An internal error occurred during: "Installing Software". xxxxxxxxx

    就是你自己本来就有那个插件了 百度怎么删吧.... 看一下我这个文章 强烈建议本地安装的时候用第四种安装 http://www.cnblogs.com/ydymz/articles/7203260.h ...

  6. struts框架从.jsp页面直接访问action

    <%@ page language="java" pageEncoding="UTF-8"%><%String path = request. ...

  7. jsp&servlet——session监听

    session监听,需要实现HttpSessionAttributeListener接口 attributeAdded:监听添加session attributeRemoved:监听删除session ...

  8. python3.6 使用 pymysql 连接 Mysql 数据库及 简单的增删改查操作

    1.通过 pip 安装 pymysql 进入 cmd  输入  pip install pymysql   回车等待安装完成: 安装完成后出现如图相关信息,表示安装成功. 2.测试连接 import ...

  9. Android Studio: You need to use a Theme.AppCompat theme (or descendant) with this activity.

    错误描述为: java.lang.IllegalStateException: You need to use a Theme.AppCompat theme (or descendant) with ...

  10. Maven之(六)setting.xml配置文件详解

    setting.xml配置文件 maven的配置文件settings.xml存在于两个地方: 1.安装的地方:${M2_HOME}/conf/settings.xml 2.用户的目录:${user.h ...