问题
How I can make my ImageButton change its color when I click it?
I want to do something like this :
Button(Blue) -> Click -> Button(Red) -> Click -> Button(Blue) -> Click -> Button(Red)
when I click it switch color and when I click again it goes back to original.
I've tried to do like this:
mTrashFlag = !mTrashFlag;
ImageButton bt = (ImageButton)findViewById(R.id.trash_button);
if(!mTrashFlag)
{
bt.setBackgroundColor(0x4CB8FB);
}
else
{
bt.setBackgroundColor(0xff0000);
}
but it didnt work. It changed color to white and then I couldn't click on it again.
回答1:
You should pass a Color class attribute instead of the hexa code directly :
if(!mTrashFlag)
{
bt.setBackgroundColor(Color.parseColor("#4CB8FB"));
}
else
{
bt.setBackgroundColor(Color.RED);
}
Also, you have to register a OnClickListener on the button to get notified when it's clicked, so the final code is :
bt.setOnClickListener(new View.OnClickListener() {
// 'v' is the clicked view, which in this case can only be your button
public void onClick(View v) {
mTrashFlag = !mTrashFlag;
if (!mTrashFlag)
{
v.setBackgroundColor(Color.parseColor("#4CB8FB"));
}
else
{
v.setBackgroundColor(Color.RED);
}
}
});
回答2:
You can use following way..
String color = "b";
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.buttonlayout);
btn = (Button) findViewById(R.id.btn);
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
onButtonClick(R.id.btn);
}
});
}
public void onButtonClick(int id) {
if (color.equals("b")) {
findViewById(id).setBackgroundColor(Color.RED);
color = "r";
} else if (color.equals("r")) {
findViewById(id).setBackgroundColor(Color.BLUE);
color = "b";
}
}
回答3:
you Can Try This code:
ImageButton mButton;
int mTrashFlag=0;
**get the id and implement the on click listener**
mButton=(ImageButton)findViewById(R.id.bt);
mButton.setOnClickListener(this);
public void onClick(View v) {
// TODO Auto-generated method stub
if(mTrashFlag==0){
mButton.setBackgroundColor(Color.BLUE);
mTrashFlag =1;
}
else if(mTrashFlag==1){
mTrashFlag=0;
mButton.setBackgroundColor(Color.RED);
}
}
回答4:
Just include the alpha value (FF)
so bt.setBackgroundColor(0x4CB8FB);
will bebt.setBackgroundColor(0xFF4CB8FB);
来源:https://stackoverflow.com/questions/20161839/imagebutton-change-background-colour-on-click