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

前端 未结 30 2234
情歌与酒
情歌与酒 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:06

    Here is my code. The idea is that ImageView gets color filter when user touches it, and color filter is removed when user stops touching it.

    Martin Booka Weser, András, Ah Lam, altosh, solution doesn't work when ImageView has also onClickEvent. worawee.s and kcoppock (with ImageButton) solution requires background, which has no sense when ImageView is not transparent.

    This one is extension of AZ_ idea about color filter.

    class PressedEffectStateListDrawable extends StateListDrawable {
    
        private int selectionColor;
    
        public PressedEffectStateListDrawable(Drawable drawable, int selectionColor) {
            super();
            this.selectionColor = selectionColor;
            addState(new int[] { android.R.attr.state_pressed }, drawable);
            addState(new int[] {}, drawable);
        }
    
        @Override
        protected boolean onStateChange(int[] states) {
            boolean isStatePressedInArray = false;
            for (int state : states) {
                if (state == android.R.attr.state_pressed) {
                    isStatePressedInArray = true;
                }
            }
            if (isStatePressedInArray) {
                super.setColorFilter(selectionColor, PorterDuff.Mode.MULTIPLY);
            } else {
                super.clearColorFilter();
            }
            return super.onStateChange(states);
        }
    
        @Override
        public boolean isStateful() {
            return true;
        }
    }
    

    usage:

    Drawable drawable = new FastBitmapDrawable(bm);
    imageView.setImageDrawable(new PressedEffectStateListDrawable(drawable, 0xFF33b5e5));
    

提交回复
热议问题