带按钮的相对布局
我想动态添加按钮数量到RelativeLayout,但我的代码不起作用。它将它们添加到显示屏上的同一位置。
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);
}
}
}
我应该修复什么才能使其正常工作?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
你有几个问题。首先,您需要为每个按钮创建新的布局参数,以避免 @rogerkk 指出的问题。其次,您尝试对第一个按钮使用零 ID。这是行不通的。
这是修复这两个问题的函数的重写。
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.