0
我想动态地将一些按钮添加到RelativeLayout,但我的代码不起作用。它将它们添加到显示屏上的相同位置。RelativeLayout with buttons
private void createButtons() {
buttons = new ArrayList<Button>();
RelativeLayout bg = (RelativeLayout) findViewById(R.id.Bg);
RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
for(int i = 0; i < channels.size(); i++){
Button newButton = new Button(this);
newButton.setId(i);
newButton.setText(channels.get(i).getTitle());
buttons.add(newButton);
if(i > 0){
lp.addRule(RelativeLayout.RIGHT_OF, i-1);
bg.addView(newButton, lp);
}else{
bg.addView(newButton);
}
}
}
我该如何解决才能使其工作?
由于您为每次迭代调用lp.addRule(),您的LayoutParams不会为每次迭代包含一个(冲突)规则。也许应该在每次迭代中实例化LayoutParams? – rogerkk 2011-03-17 18:27:29