J. K. J. K. - 5 months ago 18
Android Question

How can I change button color (png) when pressed down programmatically?

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.

Answer

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;
    }
});