[英]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() { 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. changeBackgroundColor方法正在运行,我只需要知道它们当前必须能够调用该背景的背景即可。
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: 在onCreate或类似的:
When instantiating the Button you need to set the tag first to the initial color: 实例化Button时,您需要首先将标签设置为初始颜色:
button.setTag("blue");
Inside Onclick 内部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.
我在xm中将背景设置为android.R.color.black。 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. 它要求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.