Highlight a button when it pressed without using two drawable?

非 Y 不嫁゛ 提交于 2019-12-06 05:29:05

问题


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 ?


回答1:


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



回答2:


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



回答3:


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 !




回答4:


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



来源:https://stackoverflow.com/questions/11760943/highlight-a-button-when-it-pressed-without-using-two-drawable

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