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

前端 未结 30 2335
情歌与酒
情歌与酒 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 02:03

    Thanks for the help on this thread. However, you missed one thing...you need to handle the ACTION_CANCEL as well. If you don't then you might not properly restore the alpha value of the ImageView in the event that a parent view in the view hierarchy intercepts a touch event (think a ScrollView wrapping you ImageView).

    Here is a complete class that is based off the above class but takes care of the ACTION_CANCEL as well. It uses an ImageViewCompat helper class to abstract the differences in the pre-post JellyBean API.

    public class ChangeAlphaOnPressedTouchListener implements OnTouchListener {
    
        private final float pressedAlpha;
    
        public ChangeAlphaOnPressedTouchListener(float pressedAlpha) {
            this.pressedAlpha = pressedAlpha;
        }
    
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            ImageView iv = (ImageView) v;
            switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                ImageViewCompat.setAlpha(iv, pressedAlpha);
                break;
    
            case MotionEvent.ACTION_MOVE:
                if (isInsideViewBounds(v, event)) {
                    ImageViewCompat.setAlpha(iv, pressedAlpha);
                } else {
                    ImageViewCompat.setAlpha(iv, 1f);
                }
                break;
            case MotionEvent.ACTION_UP:
                ImageViewCompat.setAlpha(iv, 1f);
                break;
            case MotionEvent.ACTION_CANCEL:
                ImageViewCompat.setAlpha(iv, 1f);
            }
            return false;
        }
    
        private static boolean isInsideViewBounds(View v, MotionEvent event) {
            return event.getX() > 0 && event.getX() < v.getWidth() && event.getY() > 0
                    && event.getY() < v.getHeight();
        }
    }
    

提交回复
热议问题