尽管我遇到了许多有关相对布局和以编程方式添加子视图的问题,但我无法解决这个问题
for (int i=0; i<views; i++) {
ImageView img = new ImageView(this);
LayoutParams img_params= new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
img_params.addRule(RelativeLayout.ALIGN_PARENT_LEFT|RelativeLayout.ALIGN_PARENT_TOP, RelativeLayout.TRUE);
relativeLayout.addView(img, img_params);
TextView textview = new TextView(this);
LayoutParams text_params= new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
text_params.addRule(RelativeLayout.ALIGN_PARENT_RIGHT|RelativeLayout.ALIGN_PARENT_TOP, RelativeLayout.TRUE);
relativeLayout.addView(textview, text_params);
}
我在下面添加了日志:
06-27 11:16:38.849: E/AndroidRuntime(20595): java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first.
您在循环中一遍又一遍地添加相同的 View 对象。第一次运行循环时,两个视图被添加,并且它们现在有一个父视图。它们无法再次添加。
您需要在每次迭代中实例化这些视图的新实例才能使其正常工作。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)