添加子视图相对布局
虽然我经历过的许多问题就相对布局和编程添加子视图,我无法来解决这个问题下面添加子视图相对布局
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对象。第一次循环运行两个视图被添加,他们现在有一个父。他们不能再次添加。
您需要在每次迭代中实例化这些视图的新实例才能使其工作。
我已编辑它,请检查 – techieWings
@newBee您不能使用'new ImageView()'。视图没有默认构造函数。将上下文传递给构造函数。使用'新的ImageView(上下文)'。对TextView执行相同的操作。 – Akash
循环
for (int i = 0; i < views; i++) {
LayoutParams img_params= new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
img_params.addRule(RelativeLayout.ALIGN_PARENT_LEFT|RelativeLayout.ALIGN_PARENT_TOP, RelativeLayout.TRUE);
ImageView img = new ImageView(this);
relativeLayout.addView(img, img_params);
LayoutParams text_params= new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
text_params.addRule(RelativeLayout.ALIGN_PARENT_RIGHT|RelativeLayout.ALIGN_PARENT_TOP, RelativeLayout.TRUE);
TextView textview = new TextView(this);
relativeLayout.addView(textview, text_params);
}
即时通讯做的.. – techieWings
你的IMG和TextView的已经在任意视图里面加创建的
ImageView
和TextView
新的实例。你应该为每一个新的添加创建新的图像和TextView对象,或者先从前一个父视图中删除你的视图 – DimmergDimmerg ...我想要在我的父级布局中的所有视图。和视图数量未知 – techieWings