[英]How can I check which background my button has (between various drawable xml i designed) in my code so that i can modify it?
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();
}
}
});
changeBackgroundColor方法正在运行,我只需要知道它们当前必须能够调用该背景的背景即可。
您可以根据设置的颜色来设置按钮的标签,并获取标签以检查其当前是蓝色还是红色。
在onCreate或类似的:
实例化Button时,您需要首先将标签设置为初始颜色:
button.setTag("blue");
内部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
}
尽管公认的答案是正确的,但它似乎并不十分优雅(我个人认为)。 这是我的代码,它充当切换按钮。 我在xm中将背景设置为android.R.color.black。 更改背景需要两个步骤。 首先获取当前背景。 其次比较并更改它。 这样的事情应该起作用:
它要求Api级别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));
}
}
};
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.