1

I am trying to create a GridLayout with 16 x 16 buttons in it, but I can't remove the spaces between the buttons.

I saw this but it didn't work.

Here's what I'm trying now:

public class MyActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.my_activity);
    GridLayout v = (GridLayout)findViewById(R.id.myGrid);
    v.setPadding(0, 0, 0, 0);
    v.setUseDefaultMargins(false);
    v.setAlignmentMode(GridLayout.ALIGN_BOUNDS);
    v.setRowOrderPreserved(false);
    Random r = new Random();
    for (int row = 0; row < 16; row++)
        for (int col = 0; col < 16; col++) {
            GridLayout.LayoutParams lp = new GridLayout.LayoutParams();
            lp.setMargins(0, 0, 0, 0);
            lp.rowSpec = GridLayout.spec(row);
            lp.columnSpec = GridLayout.spec(col);
            lp.width = 40;
            lp.height = 40;
            Button b = new Button(this);
            b.setWidth(40);
            b.setHeight(40);
            b.setText(Integer.toString(r.nextInt(10)));
            b.setPadding(0, 0, 0, 0);
            b.setLayoutParams(lp);
            v.addView(b, lp);
        }
}

Screenshot Screenshot

Any idea what's wrong?

EDIT: I changed the background of some buttons to a green picture is this is what I got:

Doh!

Apparently the spacing is part of the button image... Why Android, why?

Community
  • 1
  • 1

1 Answers1

0

Because you expect that each item has fixed width and fixed height, so it goes wrong here. Try this:

GridLayout.LayoutParams lp = new GridLayout.LayoutParams();
            lp.setMargins(0, 0, 0, 0);
            lp.rowSpec = GridLayout.spec(row);
            lp.columnSpec = GridLayout.spec(col);
            //lp.width = 40;
            //lp.height = 40;
            Button b = new Button(this);
            //b.setWidth(40);
            //b.setHeight(40);
            b.setText(Integer.toString(r.nextInt(10)));
            b.setPadding(0, 0, 0, 0);
            b.setLayoutParams(lp);
            v.addView(b, lp);
}
NamNH
  • 1,752
  • 1
  • 15
  • 37
  • I couldn't find a constructor GridLayout.LayoutParams(int, int), but commenting "lp.width = 40" or even setting it to GridLayout.LayoutParams.WRAP_CONTENT didn't work for me. – Ricardo Fodra Nov 05 '15 at 02:05
  • The idea is you try to set fixed height and width to the button, so it goes wrong. I haven't try this but you can remove all fixed height and width. Please see my edited answer. – NamNH Nov 05 '15 at 02:39