Question

I have created a TableLayout and then I created TableRow dynamically in my java code, and added some buttons in the form of an 8x8 grid. But I want to reduce the space between the buttons. I tried setting LayoutParam for the TableRow , but when I do this , the output shows just a blank screen. Here's my code:

LayoutParams param= new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT);
    field=new Button[8][8];
    tb=new TableLayout(this);
    param.setMargins(10, 2, 10, 2);

    for (int i = 0; i < field.length; i++) {
        TableRow current=new TableRow(this);
        for (int j = 0; j < field[i].length; j++) {
            Button button=new Button(this);
            field[i][j]=button;
            button.setWidth(40);
            button.setHeight(40);
            button.setLayoutParams(param);
            current.addView(button);
        }
        tb.addView(current);
    }
    t.addView(tb);

But when I don't write button.setLayoutParams(param) I get an output like this:

enter image description here

which is the normal output except that I want the space between the buttons reduced.

Was it helpful?

Solution

The spacing you're seeing is padding built into the standard Android button background asset. You can see that your layout is correct by turning on "Show Layout Bounds" in Settings > Developer Options. You just need to make your own button asset, or if a simple color is all that is needed, then just set the button background to be a color.

OTHER TIPS

In the param.setMargins() call, use negative values as necessary to get past what seems to be some natural spacing. You will also want to give the same layout margins to the table layout, and use WRAP_CONTENT for both the width and height. I am not sure if variable "t" is needed as I created the buttons without it using a TableLayout in an XML file. (I also did a 5x5 grid to fit onto my screen.)

LayoutParams param= new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
field=new Button[5][5];
tb=new TableLayout(this);

// these are the two important changes
param.setMargins(-5, -5, -5, -5);
tb.setLayoutParams(param);


for (int i = 0; i < field.length; i++) {
    TableRow current=new TableRow(this);
    for (int j = 0; j < field[i].length; j++) {
        Button button=new Button(this);
        field[i][j]=button;
        button.setWidth(40);
        button.setHeight(40);
        button.setLayoutParams(param);
        current.addView(button);
    }
    tb.addView(current);
}
t.addView(tb);

enter image description here

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top