How to set button click effect in Android?

后端 未结 14 2340
佛祖请我去吃肉
佛祖请我去吃肉 2020-11-28 01:29

In Android, when I set background image to Button, I can not see any effect on button.

I need some effect on button so user can recognize that button is clicked.

14条回答
  •  攒了一身酷
    2020-11-28 02:06

    Or using only one background image you can achive the click effect by using setOnTouchListener

    Two ways

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

    And if you don't want to use setOnTouchLister, the another way of achieving this is

        myButton.getBackground().setColorFilter(.setColorFilter(0xF00, Mode.MULTIPLY);
    
        StateListDrawable listDrawable = new StateListDrawable();
        listDrawable.addState(new int[] {android.R.attr.state_pressed}, drawablePressed);
        listDrawable.addState(new int[] {android.R.attr.defaultValue}, myButton);
    
        myButton.setBackgroundDrawable(listDrawable);
    

提交回复
热议问题