本文介绍了安卓:拉伸行TableLayout编程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想要动态地创建一个TableLayout有其所有的行像伸展显示的。我通过XML来实现它,但我想从活动做到这一点。这里是code我试过到目前为止没有成功:

I'm trying to create a TableLayout dynamically which has all its rows stretched like shown in this tutorial. I've accomplished it via XML, but I'd like to do it from the Activity. Here is the code I've tried so far without success:

public View getTableWithAllRowsStretchedView() {
    LinearLayout linearLayout = new LinearLayout(this);
    linearLayout.setOrientation(LinearLayout.VERTICAL);
    linearLayout.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.FILL_PARENT));

    TableLayout tableLayout = new TableLayout(this);
    tableLayout.setStretchAllColumns(true);
    tableLayout.setLayoutParams(new TableLayout.LayoutParams(TableLayout.LayoutParams.FILL_PARENT, TableLayout.LayoutParams.FILL_PARENT));
    tableLayout.setWeightSum(4);


    for (int i = 0; i < 4; i++) {
        TableRow tableRow = new TableRow(this);
        tableRow.setGravity(Gravity.CENTER);
        tableRow.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.FILL_PARENT, TableRow.LayoutParams.FILL_PARENT, 1.0f));

        for (int j = 0; j < 4; j++) {
            Button button = new Button(this);
            final int buttonNumber = (j + i * 4);
            button.setText("" + buttonNumber);
            button.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.FILL_PARENT, TableRow.LayoutParams.FILL_PARENT));

            tableRow.addView(button);
        }
        tableLayout.addView(tableRow);
    }

    linearLayout.addView(tableLayout);
    return linearLayout;
}

非常感谢你提前。

Thank you very much in advance.

修改

EDIT

Screenshot of what I have

what I expect

推荐答案

您行需要父母的的LayoutParams

tableRow.setLayoutParams(new TableLayout.LayoutParams(
                    TableLayout.LayoutParams.FILL_PARENT,
                    TableLayout.LayoutParams.FILL_PARENT, 1.0f));

这篇关于安卓:拉伸行TableLayout编程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-22 12:08