user1527152
user1527152

Reputation: 966

Change background of all buttons

I would like to change the background of all the Buttons in a View.

android:background="@drawable/button_red"

And i would like to do this in an OnClick() event.

android:onClick="ChangeCouleur"

I would like to do this in a foreach loop, but i am not sure how to do this.

For example:

for( b in ... )
    if (b.getid()!=idofthebutton)
         b.setbackgroud(button_red)

Thanks for any help!

Upvotes: 1

Views: 286

Answers (5)

Akshay
Akshay

Reputation: 2534

Create .XML file in your “res/drawable/” and use selector attribute in it.And use different images for the button.Please refer this link.

http://www.mkyong.com/android/android-imagebutton-selector-example/

This will clear your idea. :)

Upvotes: 1

Andy Res
Andy Res

Reputation: 16043

Put all your Buttons in an Array of Buttons, then cycle to it an change the background.

Button button1 = (Button)this.findViewById(...);
Button button2 = (Button)this.findViewById(...);
Button button3 = (Button)this.findViewById(...);

Button[] buttons={button1, button2, button3};

for (Button currentButton : buttons) {
    currentButton.setBackgroundResource(R.drawable.my_new_background);
}

Upvotes: 4

Jason Crosby
Jason Crosby

Reputation: 3583

You will have to get a reference to all the Buttons. Add them to an ArrayList or something similar. In your ChangeCouleur method use a loop to iterate through all the buttons changing the color of each one.

Upvotes: 1

Ron
Ron

Reputation: 24235

For changing the background of the clicked button

public void changeColor(View v) {
    v.setBackground(btn_red);
}

Upvotes: 1

user377628
user377628

Reputation:

One thing you could do is subclass Button, then make all the buttons in you app instances of your new class. That way, if you decide that you want to adjust the color or change something else, you only have to do it once, and it will change all the buttons in your app. Here's a question that should give you some pointers on how to do that.

Upvotes: 1

Related Questions