动态添加多个Button到多个LinearLayout
我想动态添加按钮到不同的 LinearLayout (使用 Java),但在此之前我必须将 LinearLayout
添加到主视图,顺便说一下,它也是一个 LinearLayout
。
这是我的代码:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.game);
globalLinear = (LinearLayout) findViewById(R.id.viewButtons);
LayoutInflater inflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
LinearLayout row = (LinearLayout) inflater.inflate(R.layout.row_buttons, globalLinear);
for(int i = 1; i <= nbButton; i++) {
if(i % 3 == 0) {
row = (LinearLayout) inflater.inflate(R.layout.row_buttons, globalLinear);
}
Button b = new Button(this);
int number = generator.nextInt(complexity);
b.setText(number+"");
row.addView(b, new LayoutParams(LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT) );
}
}
R.id.viewButtons
是里面的主要(垂直)LinearLayout
。 R.layout.row_buttons
是水平LinearLayout
。
正如您在上面所看到的,我尝试使用 (i % 3 == 0)
为每个 LinearLayout
获取 3 个按钮 但似乎从未创建新的 LinearLayout 。
感谢您的帮助 :)
I would like to add buttons to different LinearLayout dynamically (with Java) but before that I have to add LinearLayout
to the main View which is also a LinearLayout
by the way.
Here is my code:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.game);
globalLinear = (LinearLayout) findViewById(R.id.viewButtons);
LayoutInflater inflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
LinearLayout row = (LinearLayout) inflater.inflate(R.layout.row_buttons, globalLinear);
for(int i = 1; i <= nbButton; i++) {
if(i % 3 == 0) {
row = (LinearLayout) inflater.inflate(R.layout.row_buttons, globalLinear);
}
Button b = new Button(this);
int number = generator.nextInt(complexity);
b.setText(number+"");
row.addView(b, new LayoutParams(LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT) );
}
}
R.id.viewButtons
is the main (vertical) LinearLayout
inside.R.layout.row_buttons
is a horizontal LinearLayout
.
As you can see above, I am trying to get 3 buttons per LinearLayout
with (i % 3 == 0)
But it seems new LinearLayout
are never created.
Thank you for your help :)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可能需要定义线性布局,在循环内创建它的新实例,以便只要循环执行就可以创建它。
You might need to define the linear layout, create new instance of it within the loop for it to be created as long as the loop execute.