4

before I use two drawable one when the button state is pressed and an another another as default. so I'm fabricating a hole new image just for simple effect ! So now I'm asking...

is it possible to applicate (a color filter or any effect) on the button drawable when that button is pressed ?

M'hamed
  • 2,508
  • 3
  • 24
  • 41

4 Answers4

3

Or you can also rather than using setOnClickListner use setOnTouchListener to gain the desired effect using only one image

((Button)findViewById(R.id.testBth)).setOnTouchListener(new OnTouchListener() {

      @Override
        public boolean onTouch(View v, MotionEvent event) {
          switch (event.getAction()) {
          case MotionEvent.ACTION_DOWN: {
              Button view = (Button) v;
              view.getBackground().setColorFilter(0x77000000, PorterDuff.Mode.SRC_ATOP);
              v.invalidate();
              break;
          }
          case MotionEvent.ACTION_UP:
              // Your action here on button click
          case MotionEvent.ACTION_CANCEL: {
              Button view = (Button) v;
              view.getBackground().clearColorFilter();
              view.invalidate();
              break;
          }
          }
          return true;
        }
    });
Vinayak Bevinakatti
  • 40,205
  • 25
  • 108
  • 139
2

If your button is the standard gray background you can apply a filter in the onClick method for the button to change the color...

import android.graphics.PorterDuff;
button.getBackground().setColorFilter(0xFF00FF00, PorterDuff.Mode.MULTIPLY);  //Green

To clear the filter later:

button.getBackground().clearColorFilter();
Barak
  • 16,318
  • 9
  • 52
  • 84
  • the idea of filter is nice, but it's implimentation on click is not good cause the button can be pressed but not clicked... can I listen the press action ? – M'hamed Aug 01 '12 at 23:17
  • I'm sure you can, I've not done that before so I have no firsthand experience to share regarding it. – Barak Aug 01 '12 at 23:45
2

I found the best way to do it !

Drawable drawableNotPressed = button.getBackground(); 
Drawable drawable = drawableNotPressed.getCurrent();

//use a filter 
drawable.setColorFilter(0xF00, Mode.MULTIPLY);
StateListDrawable listDrawable = new StateListDrawable();
listDrawable.addState(new int[] { android.R.attr.state_pressed }, drawable);
listDrawable.addState(new int[] { android.R.attr.defaultValue }, drawableNotPressed );
button.setBackgroundDrawable(listDrawable);

et Voila !

Mark
  • 7,167
  • 4
  • 44
  • 68
M'hamed
  • 2,508
  • 3
  • 24
  • 41
1

You can try to change the button's style in one of the setOn*Listener Methods

Hans Hohenfeld
  • 1,729
  • 11
  • 14