Highlight a button when it pressed without using two drawable?

僤鯓⒐⒋嵵緔 提交于 2019-12-04 11:20:35

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

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;
        }
    });
M'hamed

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 !

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!