Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android: Stretching rows in TableLayout programmatically

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

enter image description here

what I expect

enter image description here

like image 300
Javier Vilar Avatar asked Dec 07 '22 15:12

Javier Vilar


1 Answers

Your rows need the parent's LayoutParams:

tableRow.setLayoutParams(new TableLayout.LayoutParams(
                    TableLayout.LayoutParams.FILL_PARENT,
                    TableLayout.LayoutParams.FILL_PARENT, 1.0f));
like image 132
user Avatar answered Jan 05 '23 01:01

user