Cameron Gunn
Cameron Gunn

Reputation: 5

Can't get this array to work

I want to create a grid of buttons for my Android app. I used a conventional for loop to create it, which usually works in other languages etc. But when i test my app, it doesn't respond and closes when the page is loading. How can i fix this...

but = new Button[4][4];
linearLayout = (ViewGroup) findViewById(R.id.buttonlayout);
for (int r = 0; r<but.length; r++) {
   for (int c = 0; c<but.length; c++) {
      but[r][c].setLayoutParams(new LinearLayout.LayoutParams(20, 20));
      but[r][c] = new Button(this);
      but[r][c].setX(20 * r);
      but[r][c].setY(20 * c);
      but[r][c].setText(" ");
      linearLayout.addView(but[r][c]);
   }
}

Upvotes: 0

Views: 65

Answers (1)

Dimmerg
Dimmerg

Reputation: 2138

but = new Button[4][4];
linearLayout = (ViewGroup) findViewById(R.id.buttonlayout);
for (int r = 0; r<but.length; r++){
for (int c = 0; c<but.length; c++){
but[r][c] = new Button(this); // you should create your object before set layout!!
but[r][c].setLayoutParams(new LinearLayout.LayoutParams(20, 20));
but[r][c].setX(20 * r);
but[r][c].setY(20 * c);
but[r][c].setText(" ");
linearLayout.addView(but[r][c]);

Upvotes: 3

Related Questions