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

时间:2016-11-15 01:24:46

标签: java android tablelayout tablerow

enter image description here

我创建了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(rows = 2,columns = 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);
        }
    }
}

如何更改代码,以便获得预期的结果&#39;?

1 个答案:

答案 0 :(得分:1)

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