3 回答

TA貢獻2011條經驗 獲得超2個贊
一個簡單的答案是在每次迭代中只添加 3 個按鈕。我的情況是這是最后一次迭代,添加的按鈕更少,只需添加更少:
LinearLayout mainLayout = new LinearLayout(this);
mainLayout.setOrientation(LinearLayout.VERTICAL);
int totalItems = 13;
for (int k=0; k<totalItems; k+=3)
{
LinearLayout layout = new LinearLayout(this);
layout.setOrientation(LinearLayout.HORIZONTAL);
layout.setTag(k/3);
int numberOfButtonsInRow = (k + 3 < totalItems) ? 3 : totalItems % 3;
for(int l = 0; l < numberOfButtonsInRow; l++)
{
Button b = new Button(this);
b.setTag(k + l);
b.setText("Button " + (k + l));
layout.addView(b);
}
mainLayout.addView(layout);
}
此外,我建議將內部循環的內容提取到一個單獨的函數中,盡管我將其留在這里是為了使其簡短。

TA貢獻2051條經驗 獲得超10個贊
解決方案:
LinearLayout ll_rootOBJ = findViewById(R.id.ll_root);
LinearLayout mainLayout = new LinearLayout(this);
mainLayout.setOrientation(LinearLayout.VERTICAL);
for (int k=0; k<13; k++)
{
LinearLayout ll = new LinearLayout(this);
ll.setOrientation(LinearLayout.HORIZONTAL);
ll.setTag(k);
for (int i=1; i<4; i++) {
Button b = new Button(this);
b.setTag(k);
b.setText("Button");
ll.addView(b);
}
mainLayout.addView(ll);
}
ll_rootOBJ.addView(mainLayout);
這將給出你想要的。快樂編碼..
這是你想要的嗎?(在這張圖中)
添加回答
舉報