Unpossible
Unpossible

Reputation: 10697

Dynamic Layout setLayoutParams Not Being Set

I have a routine that creates TableRows dynamically inside a TableLayout that is inflated from XML. I am trying to set the TableRows to be a specific width, filling them with a custom button (ButtonElement)... but nothing is showing up. Logging out the TableRow width, and it seems that it is set to 0, which might explain why it is not being displayed.

final Drawable normalBtnBg = getResources().getDrawable(R.drawable.button_states);
TableRow tableRow;
for (int x = 0; x < xDim; x++) {
    tableRow = new TableRow(this);
    tableRow.setLayoutParams(new TableLayout.LayoutParams(400, 20));
    for (int y = 0; y < yDim; y++) {
        // create the new button
        mButtons[x][y] = new ButtonElement(this, x, y);
        mButtons[x][y].setBackgroundDrawable(normalBtnBg);
        mButtons[x][y].setLayoutParams(new LayoutParams(20, 20));

        // add the button to the TableLayout
        tableRow.addView(mButtons[x][y]);
    }

    // add the TableRow to the table
    mButtonGrid.addView(tableRow, new TableLayout.LayoutParams(400, 20));
    Log.d(LOG_TAG, "trWidth - " + tableRow.getWidth());
}

tableRow.getWidth() always returns a value of 0... I have verified the buttons are being generated, as if I add them directly to the mButtonGrid, they are displayed (of course, not in a TableRow, just vertically down).

Any help appreciated.

EDIT:

Figured this out, see my answer below.

Upvotes: 0

Views: 3280

Answers (1)

Unpossible
Unpossible

Reputation: 10697

FYI, solved this issue... I was using TableLayout.LayoutParams, but needed to use the TableRow.LayoutParams to make it work (from here):

final Drawable normalBtnBg = getResources().getDrawable(R.drawable.button_states);
TableRow tableRow;
for (int x = 0; x < xDim; x++) {
    tableRow = new TableRow(this);
    tableRow.setLayoutParams(new TableRow.LayoutParams(400, 20));
    for (int y = 0; y < yDim; y++) {
        // create the new button
        mButtons[x][y] = new ButtonElement(this, x, y);
        mButtons[x][y].setBackgroundDrawable(normalBtnBg);
        mButtons[x][y].setLayoutParams(new TableRow.LayoutParams(20, 20));

        // add the button to the TableLayout
        tableRow.addView(mButtons[x][y]);
    }

    // add the TableRow to the table
    mButtonGrid.addView(tableRow, new TableLayout.LayoutParams(400, 20));
}

Upvotes: 2

Related Questions