Button button1 = new Button(this);
LinearLayout lay1 = findViewById(R.id.buttonLay)
for (int x = 1; x <= 4; x++) {
Button button1 = new Button(this);
}
这是我的代码。 如何将button1添加到lay1?
答案 0 :(得分:1)
首先获取将包含按钮的父级布局,例如:
LinearLayout layout = findViewById(R.id.yourlayout);
您将需要类似列表的内容来存储按钮:
List<Button> list = new ArrayList<>();
然后循环:
for (int x = 1; x <= 4; x++) {
Button button = new Button(this);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// code
}
});
list.add(button);
layout.addView(button);
}
实例化每个按钮后, 将其添加到列表中以备后用 将其添加到父布局。