Pedro Destri Pedro Destri - 5 months ago 47
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(;
btns[1] = (Button) findViewById(;
btns[2] = (Button) findViewById(;
btns[3] = (Button) findViewById(;

btns[4] = (Button) findViewById(;
btns[5] = (Button) findViewById(;
btns[6] = (Button) findViewById(;
btns[7] = (Button) findViewById(;

btns[8] = (Button) findViewById(;
btns[9] = (Button) findViewById(;
btns[10] = (Button) findViewById(;
btns[11] = (Button) findViewById(;

btns[12] = (Button) findViewById(;
btns[13] = (Button) findViewById(;
btns[14] = (Button) findViewById(;
btns[15] = (Button) findViewById(;

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.


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

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.