button1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (//button1 background is blue){
changeBackgroundColorRed();
}
else if (//button1 background is red){
changeBackgroundColorBlue();
}
}
});
The changeBackgroundColor methods are working I just need to know which background they currently have to be able to call the method.
You can set the tag of the button depending of what color you have set and get the Tag to check if its currently blue or red.
In onCreate or similar:
When instantiating the Button you need to set the tag first to the initial color:
button.setTag("blue");
Inside Onclick
if (button.getTag().equals("blue")){ //background is currently blue
changeBackgroundColorRed();
button.setTag("red"); //set the Tag to red cause you change the background to red
}
else if (button.getTag().equals("red")){ //background is currently red
changeBackgroundColorBlue();
button.setTag("blue"); //set the Tag to blue cause you change the background to blue
}
Though the accepted answer is correct it has it doesnot seem to be very elegant(my personal opinion). Heres my code and it acts as a toggle button. I have set background to android.R.color.black in xm. Changing background requires two steps. First get the current background. Second compare and change it. Something like this should work:
It requires Api level 11.
public class Sample extends Activity {
Button button1;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.sample);
button1 = (Button) findViewById(R.id.button1);
button1.setOnClickListener(OnClickOKButton());
}
View.OnClickListener OnClickOKButton() {
return new View.OnClickListener() {
public void onClick(View v) {
ColorDrawable currentColor = (ColorDrawable) button1
.getBackground();
int color1 = currentColor.getColor();
if (color1 == getResources().getColor(android.R.color.black)) {
button1.setBackgroundColor(getResources().getColor(
android.R.color.darker_gray));
} else {
button1.setBackgroundColor(getResources().getColor(
android.R.color.black));
}
}
};
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.