StateListDrawable to switch colorfilters

后端 未结 5 978
傲寒
傲寒 2020-12-15 11:34

I want to create custom buttons to use in a TabHost. I haven been trying to just use the same image resource (png), but have the colorfilter change depending on the state. S

5条回答
  •  半阙折子戏
    2020-12-15 11:43

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

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

提交回复
热议问题