添加Fragment报已有父view,需先移除的错

时间:2022-03-20 05:30:10

错误LOG:

 12-13 17:05:28.754: E/AndroidRuntime(8344): FATAL EXCEPTION: main
12-13 17:05:28.754: E/AndroidRuntime(8344): java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first.
12-13 17:05:28.754: E/AndroidRuntime(8344): at android.view.ViewGroup.addViewInner(ViewGroup.java:3337)
12-13 17:05:28.754: E/AndroidRuntime(8344): at android.view.ViewGroup.addView(ViewGroup.java:3208)
12-13 17:05:28.754: E/AndroidRuntime(8344): at android.view.ViewGroup.addView(ViewGroup.java:3165)
12-13 17:05:28.754: E/AndroidRuntime(8344): at android.view.ViewGroup.addView(ViewGroup.java:3145)
12-13 17:05:28.754: E/AndroidRuntime(8344): at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:839)
12-13 17:05:28.754: E/AndroidRuntime(8344): at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:1032)
12-13 17:05:28.754: E/AndroidRuntime(8344): at android.app.BackStackRecord.run(BackStackRecord.java:622)
12-13 17:05:28.754: E/AndroidRuntime(8344): at android.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1382)
12-13 17:05:28.754: E/AndroidRuntime(8344): at android.app.FragmentManagerImpl$1.run(FragmentManager.java:426)
12-13 17:05:28.754: E/AndroidRuntime(8344): at android.os.Handler.handleCallback(Handler.java:605)
12-13 17:05:28.754: E/AndroidRuntime(8344): at android.os.Handler.dispatchMessage(Handler.java:92)
12-13 17:05:28.754: E/AndroidRuntime(8344): at android.os.Looper.loop(Looper.java:137)
12-13 17:05:28.754: E/AndroidRuntime(8344): at android.app.ActivityThread.main(ActivityThread.java:4424)
12-13 17:05:28.754: E/AndroidRuntime(8344): at java.lang.reflect.Method.invokeNative(Native Method)
12-13 17:05:28.754: E/AndroidRuntime(8344): at java.lang.reflect.Method.invoke(Method.java:511)
12-13 17:05:28.754: E/AndroidRuntime(8344): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:787)
12-13 17:05:28.754: E/AndroidRuntime(8344): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:554)
12-13 17:05:28.754: E/AndroidRuntime(8344): at dalvik.system.NativeStart.main(Native Method)

解决:

//如果是在布局文件中写了Fragment name="xx.xx.XxFragment",可以使用这种方式,如果是使用FragmentTransaction需要采用方式二的两种代码
方式一:
inflater.inflate(R.layout.reg_fragment, container);
方式二:
inflater.inflate(R.layout.reg_fragment, container, false);
inflater.inflate(R.layout.reg_fragment, null);

原因:猜想是因为attach的时候不是直接add进去的,未证实。