Pedro Destri Pedro Destri - 3 months ago 24
Android Question

Android multiple Button color changes

So, I have this problem, I'm trying to make a Button change it´s color, and the color of the other buttons that sorround it when i click on it, and it needs to stay like that, until some one clicks on it again, or until some on clicks on a button that sorrounds it. The picture makes it easier to understand. UI

so eg. when you click number 6, numbers 2,6,7,5,10 need to change its color to red, and, when you click on it again, they need to change it's color back to green.
So, I did this:

Button[] btns = new Button[16]; //colocando 16 botões nele

btns[0] = (Button) findViewById(R.id.button1);
btns[1] = (Button) findViewById(R.id.button2);
btns[2] = (Button) findViewById(R.id.button3);
btns[3] = (Button) findViewById(R.id.button4);

btns[4] = (Button) findViewById(R.id.button5);
btns[5] = (Button) findViewById(R.id.button6);
btns[6] = (Button) findViewById(R.id.button7);
btns[7] = (Button) findViewById(R.id.button8);

btns[8] = (Button) findViewById(R.id.button9);
btns[9] = (Button) findViewById(R.id.button10);
btns[10] = (Button) findViewById(R.id.button11);
btns[11] = (Button) findViewById(R.id.button12);

btns[12] = (Button) findViewById(R.id.button13);
btns[13] = (Button) findViewById(R.id.button14);
btns[14] = (Button) findViewById(R.id.button15);
btns[15] = (Button) findViewById(R.id.button16);


And now I'm a bit lost. I've built the game logic already on paper, the problem is, I don't know how to change the color of multiple buttons.

Answer

Since you say you have the logic already, I guess you only need to be shown how to change the background color of the appropriate buttons. In this case, I'd have a method that takes an array of Button objects and the color to set them to:

private void changeColorOfTheseButtons(Button[] buttons, int color){
  for(int x=0; x < buttons.length; x++){
     //change its color
     buttons[x].setBackgroundColor(color);
   }
}

Then this is how you call the method above with a color (assuming you already have the list of buttons whose color you want to change):

...
changeColorOfTheseButtons(arrayOfButtonsToChange, Color.RED);

using color RED as example above - but you can use any color in Color.*

I hope this gives you some ideas.