我遇到IllegalStateException的问题。我有一个创建的函数从LinearLayout中删除所有视图并重新创建并重新添加它们。其中一个TextView必须是静态的,以便它可以与我创建的自定义视图进行交互。当TextView第二次添加到布局时,程序将抛出IllegalStateException。稍微单步执行程序后,似乎父LinearLayout已从其子节点中删除了视图,但TextView本身仍“认为”它具有父节点。这是我的代码:(只有重要的部分)
public static TextView latchingText;
private LinearLayout layout;
private void recreateLayout(){
layout.removeView(latchingText);
layout.addView(latchingtext);
}
有没有人知道最新情况?
编辑:这是日志:
02-13 09:04:41.012: ERROR/AndroidRuntime(10489): FATAL EXCEPTION: main
02-13 09:04:41.012: ERROR/AndroidRuntime(10489): java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first.
02-13 09:04:41.012: ERROR/AndroidRuntime(10489): at android.view.ViewGroup.addViewInner(ViewGroup.java:2012)
02-13 09:04:41.012: ERROR/AndroidRuntime(10489): at android.view.ViewGroup.addView(ViewGroup.java:1907)
02-13 09:04:41.012: ERROR/AndroidRuntime(10489): at android.view.ViewGroup.addView(ViewGroup.java:1864)
02-13 09:04:41.012: ERROR/AndroidRuntime(10489): at android.view.ViewGroup.addView(ViewGroup.java:1844)
02-13 09:04:41.012: ERROR/AndroidRuntime(10489): at android.PhysicsEngine.Diagram.createTraceLayout(Diagram.java:357)
02-13 09:04:41.012: ERROR/AndroidRuntime(10489): at android.PhysicsEngine.Diagram.access$3(Diagram.java:173)
02-13 09:04:41.012: ERROR/AndroidRuntime(10489): at android.PhysicsEngine.Diagram$2.onClick(Diagram.java:270)
02-13 09:04:41.012: ERROR/AndroidRuntime(10489): at android.view.View.performClick(View.java:2405)
02-13 09:04:41.012: ERROR/AndroidRuntime(10489): at android.view.View$PerformClick.run(View.java:8813)
02-13 09:04:41.012: ERROR/AndroidRuntime(10489): at android.os.Handler.handleCallback(Handler.java:587)
02-13 09:04:41.012: ERROR/AndroidRuntime(10489): at android.os.Handler.dispatchMessage(Handler.java:92)
02-13 09:04:41.012: ERROR/AndroidRuntime(10489): at android.os.Looper.loop(Looper.java:123)
02-13 09:04:41.012: ERROR/AndroidRuntime(10489): at android.app.ActivityThread.main(ActivityThread.java:4627)
02-13 09:04:41.012: ERROR/AndroidRuntime(10489): at java.lang.reflect.Method.invokeNative(Native Method)
02-13 09:04:41.012: ERROR/AndroidRuntime(10489): at java.lang.reflect.Method.invoke(Method.java:521)
02-13 09:04:41.012: ERROR/AndroidRuntime(10489): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
02-13 09:04:41.012: ERROR/AndroidRuntime(10489): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
02-13 09:04:41.012: ERROR/AndroidRuntime(10489): at dalvik.system.NativeStart.main(Native Method)
答案 0 :(得分:2)
日志说出你需要做什么。
child.getParent().removeView(child);
这应该基本上有效。检查null,getParent()可能为null ...
一个简短的解释:布局变量不是静态的,因此用于调用removeView()
的布局变量很可能已经是另一个,因此它不适用于孩子。为了防止这种情况,您应该尝试始终通过调用getParent()
来访问父项,而不仅仅是使用可能已被新对象覆盖的成员变量。