Reputation: 14711
I have a button in my XML activity layout that uses either a blue or a red png image as its background (this is set up before opening the activity)
How do I make it turn gray (the blue png has to become gray) when pressed programmatically, without using a state drawable.
Upvotes: 0
Views: 135
Reputation: 18242
You can set a ColorMatrixColorFilter
with a saturation of 0 to the button background:
final Button mybutton = (Button) findViewById(R.id.mybutton);
mybutton.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(final View view, final MotionEvent motionEvent) {
if (motionEvent.getAction() == MotionEvent.ACTION_DOWN) {
final ColorMatrix matrix = new ColorMatrix();
matrix.setSaturation(0);
mybutton.getBackground().setColorFilter(new ColorMatrixColorFilter(matrix));
} else if (motionEvent.getAction() == MotionEvent.ACTION_UP) {
final ColorMatrix matrix = new ColorMatrix();
matrix.setSaturation(1);
mybutton.getBackground().setColorFilter(new ColorMatrixColorFilter(matrix));
}
return true;
}
});
Upvotes: 3
Reputation: 3167
You can use on touch listner for that, check below for just example which you need to modify as per your requirement.
button.setOnTouchListener(new OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_DOWN)
{
button.setBackgroundColor(Color.GRAY);
}
else if (event.getAction() == MotionEvent.ACTION_UP)
{
button.setBackgroundColor(Color.RED);
}
return false;
}
});
Upvotes: 1