Android highlight an imagebutton when clicked

后端 未结 5 885
执笔经年
执笔经年 2021-01-31 05:06

I am using an ImageButton. But I don get the highlight when clicked. I googled and many suggested to use selector where another image is displayed. Is there any way

5条回答
  •  面向向阳花
    2021-01-31 05:46

    Without having to create multiple images (pressed, normal etc) and even don't have to create selector. Use setOnTouchListener rather than setOnClickListener. The below code will give you the grey overlay on the clicked item.

     ((ImageButton)findViewById(R.id.myImageBtn)).setOnTouchListener(new OnTouchListener() {
    
          @Override
            public boolean onTouch(View v, MotionEvent event) {
              switch (event.getAction()) {
              case MotionEvent.ACTION_DOWN: {
                  ImageButton view = (ImageButton ) 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: {
                  ImageButton view = (ImageButton) v;
                  view.getBackground().clearColorFilter();
                  view.invalidate();
                  break;
              }
              }
              return true;
            }
        });
    

提交回复
热议问题