1

I'm trying to write a simple android application, In the app, I have a blank TableLayout in the xml file, and I'm dynamically (through java code) adding TableRows to the table, and Buttons to the table rows. the buttons all have background images.

Everything's perfectly fine, except the size. I want the table to fit the screen but I've had a hard time resizing the whole thing. The best I've been able to do was make the individual buttons smaller by giving them a specific size, which isn't really helpful because of different screen sizes.

I've tried to use the LayoutParams and the MATCH_PARENT parameters but it doesn't seem to do anything.

My code is something like this:

....
TableLayout table = findViewById(R.id.table);
for (int i = 0; i < count; i++) {
    TableRow row = new TableRow(this);
    for (int j = 0; j < count; j++) {
        Button cell = new Button(this);
        cell.setBackgroundResource(R.drawable.cell_background);
        row.addView(cell);
    }
    table.addView(row);
}

How can I make the cells adjust their size according to the screen?

GianhTran
  • 3,443
  • 2
  • 22
  • 42
TheStudent
  • 41
  • 1
  • 6
  • Do you know how to get the width and height of the screen? – 0xCursor Aug 04 '18 at 23:16
  • @LAD I do, but is that the only method? I feel like there should be a cleaner way of doing it. – TheStudent Aug 04 '18 at 23:20
  • So you do something like `this.getResources().getDisplayMetrics().widthPixels`? I don't know of a different way, but maybe there is. – 0xCursor Aug 04 '18 at 23:21
  • Actually, in [this post](https://stackoverflow.com/a/6521076/6214491), it shows that you can also use `Point displaySize = new Point(); activity.getWindowManager().getDefaultDisplay().getRealSize(displaySize);`. – 0xCursor Aug 04 '18 at 23:25
  • That seems right, still, If that is the only way to do it dynamically .. then I wonder if there's a way to set the size of the buttons using dp instead of px? – TheStudent Aug 04 '18 at 23:33

0 Answers0