有没有办法动态地将新按钮添加到具有唯一ID的线性布局中。考虑使用预定义按钮来执行此操作。
答案 0 :(得分:1)
LinearLayout row = new LinearLayout(this);
row.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
Button btnTag = new Button(this);
btnTag.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
btnTag.setText("Button 1");
btnTag.setId(1);
row.addView(btnTag);
layout.addView(row);
答案 1 :(得分:0)
是的,您可以动态地将按钮添加到线性布局。
例如:
LinearLayout layout = new LinearLayout(this);
layout.setLayoutParams(new AbsListView.LayoutParams(AbsListView.LayoutParams.WRAP_CONTENT,AbsListView.LayoutParams.WRAP_CONTENT));
layout.setId(5000);
Random random = new Random();
//Five button
for(int i=0;i<5;i++)
{
Button button = new Button(this);
button.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
button.setText("Button");
button.setId(random.nextInt(5)); //generate unique number between 0 to 4 and set it as id
layout.addView(button);
}