我想在 android 中动态创建一个包含一些按钮的布局。但我找不到任何方法来动态创建这个布局。
这是我的布局:
我想在按钮完全填充设备宽度后将它们放入下一行。按钮的总数可以变化。有没有办法动态地做到这一点?
更新: 根据您的建议,我正在使用此代码:
private void addQuestionPallete() {
int tempBtn = 30;
LayoutParams param = new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT, 0.1f);
LayoutParams param2 = new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT, 1f);
linearContent.setWeightSum(1f);
linearContent.setOrientation(LinearLayout.VERTICAL);
btnQuestionPalete = new Button[10];
for (int j = 0; j < tempBtn / 10; j++) {
linearQuestionPalettesRow = new LinearLayout(mContext);
linearQuestionPalettesRow.setOrientation(LinearLayout.HORIZONTAL);
linearQuestionPalettesRow.setLayoutParams(param2);
for (int i = 0; i < 10; i++) {
btnQuestionPalete[i] = new Button(mContext);
btnQuestionPalete[i].setLayoutParams(param);
btnQuestionPalete[i].setTextColor(Color.BLACK);
btnQuestionPalete[i].setText("5");
btnQuestionPalete[i].setId(fChexkBoxID++);
linearQuestionPalettesRow.addView(btnQuestionPalete[i]);
}
}
linearContent.addView(linearQuestionPalettesRow);
}
但它只显示单行按钮。我在哪里做错了?
更新 :
好的,我已经解决了我的问题。我在 for 循环中添加了布局。因此布局只添加了一次。