问题
I want to add number of buttons to RelativeLayout dynamically, but my code doesn't work. It adds them to the same place on the display.
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);
}
}
}
What should I fix to make it work?
回答1:
You have a couple of problem. First off, you need to create layout new layout params for each button to avoid the problem that @rogerkk pointed out. Second, you are trying to use an ID of zero for the first button. This will not work.
Here is a rework of the function that fixes these two problems.
private void createButtons() {
buttons = new ArrayList<Button>();
RelativeLayout bg = (RelativeLayout) findViewById(R.id.Bg);
for(int i = 0; i < channels.size(); i++){
Button newButton = new Button(this);
newButton.setId(i+1); // ID of zero will not work
newButton.setText(channels.get(i).getTitle());
buttons.add(newButton);
// New layout params for each button
RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
if(i > 0){
// using getId() here in case you change how you assign IDs
int id =buttons.get(i-1).getId();
lp.addRule(RelativeLayout.RIGHT_OF, id);
}
bg.addView(newButton,lp);
}
}
来源:https://stackoverflow.com/questions/5343299/relativelayout-with-buttons