Zoliqa
Zoliqa

Reputation: 1025

How to create a table filled with buttons for Android

I have a simple problem for Android. I'd like to create an n by n table filled with buttons. First I want to calculate the minimum of the screen's width and height (just because I want to show my table entirely on the screen). I have the following code:

Display display = getWindowManager().getDefaultDisplay(); 
int width = display.getWidth();
int height = display.getHeight();
int min = Math.min(width, height);
int buttonSize = (int)Math.floor(min / dimension);

TableLayout rootLayout = (TableLayout)this.findViewById(R.id.tableLayout1);

for (int i = 0; i < dimension; ++i)
{
  LinearLayout lLayout = new LinearLayout(this);
  lLayout.setOrientation(0);
  rootLayout.addView(lLayout);

  for (int j = 0; j < dimension; ++j)
  {
    Button b = new Button(this);
    b.setText("-");
    b.setPadding(0, 0, 0, 0);
    b.setWidth(buttonSize);
    b.setHeight(buttonSize);

    lLayout.addView(b);
  }
}

I can't figure out why the buttons' width and height don't get set. I tried to populate the table from the designer by specifying the width and height and then it worked.

Any help is really appreciated.

Upvotes: 1

Views: 273

Answers (1)

AJcodez
AJcodez

Reputation: 34146

I would set the LinearLayout.LayoutParams of each button as well? Give it a shot...

b.setLayoutParams(
    new LinearLayout.LayoutParams(width, height)
);

Upvotes: 1

Related Questions