如果每行包含不同数量的视图,如何在 tablelayout 中制作相同大小的视图?

How to make same sized views in tablelayout if each row contains different number of views?

我创建了 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);
}

然后我以编程方式创建了一个表格布局(行 = 2,列 = 3)并将其添加到我的布局中:

MyTableLayout tableLayout = new MyTableLayout(this);
tableLayout.createTableLayoutOfButtons(tableRows /*=2*/, tableCols /*=3*/, listButtons);
mylinearLayout.addView(tableLayout);

我的 MyTableLayout class 是:

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);
        }
    }
}

如何更改代码以便获得 'expected result'?

TableRow.LayoutParams 中有一个 LayoutSpan 属性,您可以在 TableRow 子项上设置它,即 listButtons.get(indexListButtons)。尝试将其设置为 1。否则,您可以尝试为其他列插入空视图。