Android: Cloning a drawable in order to make a StateListDrawable with filters

前端 未结 7 754
梦谈多话
梦谈多话 2020-11-29 18:32

I\'m trying to make a general framework function that makes any Drawable become highlighted when pressed/focused/selected/etc.

My function takes a D

7条回答
  •  有刺的猬
    2020-11-29 19:15

    This is my solution, based on this SO question.

    The idea is that ImageView gets color filter when user touches it, and color filter is removed when user stops touching it. Only 1 drawable/bitmap is in memory, so no need to waste it. It works as it should.

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

提交回复
热议问题