3 回答

TA貢獻(xiàn)2011條經(jīng)驗(yàn) 獲得超2個(gè)贊
一個(gè)簡(jiǎn)單的答案是在每次迭代中只添加 3 個(gè)按鈕。我的情況是這是最后一次迭代,添加的按鈕更少,只需添加更少:
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);
}
此外,我建議將內(nèi)部循環(huán)的內(nèi)容提取到一個(gè)單獨(dú)的函數(shù)中,盡管我將其留在這里是為了使其簡(jiǎn)短。

TA貢獻(xiàn)1859條經(jīng)驗(yàn) 獲得超6個(gè)贊
只需在另一個(gè)for循環(huán)中的“LinearLayout ll”視圖中再添加兩個(gè)按鈕

TA貢獻(xiàn)2051條經(jīng)驗(yàn) 獲得超10個(gè)贊
解決方案:
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);
這將給出你想要的??鞓?lè)編碼..
這是你想要的嗎?(在這張圖中)
添加回答
舉報(bào)