How can I give an imageview click effect like a button on Android?

前端 未结 30 2244
情歌与酒
情歌与酒 2020-11-28 01:50

I have imageview in my Android app that I am using like a button with the onClick event given, but as you might guess it is not giving imageview a clickable effect when clic

30条回答
  •  清酒与你
    2020-11-28 01:54

    You can do this with a single image using something like this:

         //get the image view
        ImageView imageView = (ImageView)findViewById(R.id.ImageView);
    
        //set the ontouch listener
        imageView.setOnTouchListener(new OnTouchListener() {
    
            @Override
            public boolean onTouch(View v, MotionEvent event) {
    
                switch (event.getAction()) {
                    case MotionEvent.ACTION_DOWN: {
                        ImageView view = (ImageView) v;
                        //overlay is black with transparency of 0x77 (119)
                        view.getDrawable().setColorFilter(0x77000000,PorterDuff.Mode.SRC_ATOP);
                        view.invalidate();
                        break;
                    }
                    case MotionEvent.ACTION_UP:
                    case MotionEvent.ACTION_CANCEL: {
                        ImageView view = (ImageView) v;
                        //clear the overlay
                        view.getDrawable().clearColorFilter();
                        view.invalidate();
                        break;
                    }
                }
    
                return false;
            }
        });
    

    I will probably be making this into a subclass of ImageView (or ImageButton as it is also a subclass of ImageView) for easier re-usability, but this should allow you to apply a "selected" look to an imageview.

提交回复
热议问题