2
如果每個行包含不同數量的視圖,如何在tablelayout中製作相同大小的視圖?
我創建4個GIF圖像按鈕,並將它們加入到GIF圖像按鈕的列表:
for (int i = 0; i < 4; ++i) {
GifImageButton myButton = new GifImageButton();
myButton.setBackgroundResource(drawables[i]); // add some drawable to the button background
myButton.setLayoutParams(new TableRow.LayoutParams(0, TableRow.LayoutParams.MATCH_PARENT, 1.0f));
listButtons.add(myButton);
}
然後創建了一個tablelayout(行數= 2,列= 3)編程並將其添加到我的佈局:
MyTableLayout tableLayout = new MyTableLayout(this);
tableLayout.createTableLayoutOfButtons(tableRows /*=2*/, tableCols /*=3*/, listButtons);
mylinearLayout.addView(tableLayout);
我MyTableLayout類:
public class MyTableLayout extends TableLayout {
public MyTableLayout(Context context) {
super(context);
}
// indexListButtons is the current index of the listButtons elements. so as long as there are buttons, we will add them to the table rows
int indexListButtons = 0;
public void createTableLayoutOfButtons(int numRows, int numCols, List<GifImageButton> listButtons) {
setLayoutParams(new TableLayout.LayoutParams(LayoutParams.MATCH_PARENT, TableLayout.LayoutParams.MATCH_PARENT));
for (int i = 0; i < numRows; ++i) {
TableRow tableRow = new TableRow(getContext());
tableRow.setGravity(Gravity.CENTER);
tableRow.setLayoutParams(new TableLayout.LayoutParams(
TableLayout.LayoutParams.MATCH_PARENT,
TableLayout.LayoutParams.MATCH_PARENT));
for (int j = 0; j < numCols; ++j, ++indexListButtons) {
// indices 0, 1, 2, 3
if (indexListButtons < listButtons.size()) {
tableRow.addView(listButtons.get(indexListButtons));
}
// indices 4, 5 don't exist
else {
// not enough buttons
}
}
addView(tableRow);
}
}
}
如何更改代碼,以便獲得「預期結果」?
我試過layoutspan,但它沒有工作..我想盡量避免插入空視圖,但它解決了它!我需要添加視圖的特定參數。謝謝! –
不錯!真高興你做到了。 – Mike