2

I have dynamically created buttons. I just want change the background color of the button which I have clicked. For example, Initially all buttons should have grey background color. If I clicked a button then clicked button background color should changed to red and other buttons background color should be in grey.

Here I have tried a bit

for (int i = 0; i < 5; i++) {
 Button myBtn = new Button(ProductDetailsActivity.this);
 myBtn.setText("My Button"+i);
 myBtn.setBackGroundColor(Color.parseColor("#cccccc"));
 myBtn.setOnClickListener(new View.OnClickListener() {
     @Override
     public void onClick(View view) {
        myBtn.setBackGroundColor(Color.parseColor("#ff0000"));
     }
});
}
Rajan Kali
  • 12,627
  • 3
  • 25
  • 37
Vignesh S
  • 21
  • 2

1 Answers1

0

Your code seems legit. But instead of

myBtn.setBackGroundColor(Color.parseColor("#ff0000"));

You can use

myBtn.setBackGroundColor(Color.RED);

I think you want to change all buttons' colors dynamically according to which one is clicked. And want to turn others to gray.

So to achieve that you need to keep buttons in an array. Then by reaching others index you can modify them. You can get the index from the end of the buttonText String and parse it to integer.

    Button[] buttonArray = new Button[4];

    for (int i = 0; i < 5; i++) {
 Button myBtn = new Button(ProductDetailsActivity.this);
 myBtn.setText("My Button"+i);
 myBtn.setBackGroundColor(Color.GREY);
 myBtn.setId(new Random().nextInt());
 myBtn.setOnClickListener(new View.OnClickListener() {
     @Override
     public void onClick(View view) {

          for(int j=0; j<buttonArray.lenght;j++){
              if(view.getId() == buttonArray[j].getId()){
                   buttonArray[j].setBackgroundColor(Color.RED);
                }else{
                   buttonArray[j].setBackgroundColor(Color.GREY);
                }
             }
     }
});
 buttonArray[i]=myBtn;
}

So the main idea is to keep all buttons in an array. If one of them clicked, get that one's index make it's background's red. And turn other buttons'(which is not that index) background grey again.

Hussien Fahmy
  • 1,119
  • 6
  • 24
Erdem Akkuzu
  • 101
  • 6