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

使用addView的时候出现下面的报错提示

01-13 03:00:44.206 4533-4533/com.ldw.crossfire E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.ldw.crossfire, PID: 4533
    java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first.
        at android.view.ViewGroup.addViewInner(ViewGroup.java:3562)
        at android.view.ViewGroup.addView(ViewGroup.java:3415)
        at android.view.ViewGroup.addView(ViewGroup.java:3360)
        at android.view.ViewGroup.addView(ViewGroup.java:3336)
        at com.ldw.crossfire.pager.menudetail.ScoreMenuDetailPager$1.onClick(ScoreMenuDetailPager.java:43)
        at android.view.View.performClick(View.java:4438)
        at android.view.View$PerformClick.run(View.java:18422)
        at android.os.Handler.handleCallback(Handler.java:733)
        at android.os.Handler.dispatchMessage(Handler.java:95)
        at android.os.Looper.loop(Looper.java:136)
        at android.app.ActivityThread.main(ActivityThread.java:5001)
        at java.lang.reflect.Method.invokeNative(Native Method)
        at java.lang.reflect.Method.invoke(Method.java:515)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
        at dalvik.system.NativeStart.main(Native Method)
		
		R.anim.slide_in_right.xml

一,报错原因
根据The specified child already has a parent. You must call removeView() on the child’s parent first.日志信息,不难读懂大致意思是子view已经拥有一个父布局,我们需要先让该子view的父布局调用一下 removeView()方法。也就是说一个子view只能拥有一个父view,这种情况往往会出现在动态添加view上,我们添加子view的时候,并不知道子view是不是已经拥有一个父view,如果说已经存在一个父view那么就会报以上错误。

二,解决方案
根据错误信息定位到是在instantiateItem此方法中,在此方法添加动态view之前,先做子view是否已经具有父view的判断,如果存在就调用 removeView()方法。

@Override
public Object instantiateItem(View container, final int position) {
	View v=views.get(position);
	ViewPager parent = (ViewPager) v.getParent();
	if (parent != null) {
		parent.removeAllViews();
	}
	((ViewPager) container).addView(views.get(position), 0);
	return views.get(position);


}

解决办法是在instantiateItem中使用如下方式:

ViewGroup parent = (ViewGroup) v.getParent();

 if (parent != null) {

parent.removeAllViews();

 } 

container.addView(v);

 

你可能感兴趣的:(Android高级进阶)