10-05 23:39:48.187: E/AndroidRuntime(12854): Caused by: java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child‘s parent first.
10-05 23:39:48.187: E/AndroidRuntime(12854): at android.view.ViewGroup.addViewInner(ViewGroup.java:1976)
10-05 23:39:48.187: E/AndroidRuntime(12854): at android.view.ViewGroup.addView(ViewGroup.java:1871)
10-05 23:39:48.187: E/AndroidRuntime(12854): at android.view.ViewGroup.addView(ViewGroup.java:1828)
10-05 23:39:48.187: E/AndroidRuntime(12854): at android.view.ViewGroup.addView(ViewGroup.java:1808)
10-05 23:39:48.187: E/AndroidRuntime(12854): at com.solar.WaterLevelActivity.InitUnitTimeLowestWaterLevel(WaterLevelActivity.java:49)
10-05 23:39:48.187: E/AndroidRuntime(12854): at com.solar.WaterLevelActivity.InitView(WaterLevelActivity.java:30)
10-05 23:39:48.187: E/AndroidRuntime(12854): at com.solar.WaterLevelActivity.onCreate(WaterLevelActivity.java:25)
10-05 23:39:48.187: E/AndroidRuntime(12854): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
10-05 23:39:48.187: E/AndroidRuntime(12854): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1611)
10-05 23:39:48.187: E/AndroidRuntime(12854): ... 11 more
补充说明:InitUnitTimeLowestWaterLevel()在OnCreate函数中被调用,用来初始化界面。实现的效果是动态添加界面。
下面是出错的代码:
1 private void InitUnitTimeLowestWaterLevel() { 2 LinearLayout listMachines = (LinearLayout) findViewById(R.id.water_level_page_water_level_setting); 3 LayoutInflater inflater = LayoutInflater.from(WaterLevelActivity.this); 4 View tlWaterLevelInfo = inflater.inflate(R.layout.unit_time_water_level_item, null); 5 listMachines.addView(tlWaterLevelInfo); 6 listMachines.addView(tlWaterLevelInfo); //这个地方出错了。 7 }
错误的原因:通过LayoutInflater实例化的一个布局(View)。被重复添加了两次。而一个View只能有一个父控件。当第二次添加的时候,又要改变这个控件的父控件(虽然是同一个父控件,但是也要通过改变该View的父控件来实现)。运行时又不允许一个有父控件的子控件在有了一个父控件时,改变他的父控件。
解决方案:重新用布局文件实例化一个子控件,再添加到父控件上。