StateListDrawable to switch colorfilters

后端 未结 5 977
傲寒
傲寒 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:41

    Here is my variation of @Malachiasz code, this lets you pick whatever combination of states and colors to apply to the base drawable.

    public class ColorFilteredStateDrawable extends StateListDrawable {
    
        private final int[][] states;
        private final int[] colors;
    
        public ColorFilteredStateDrawable(Drawable drawable, int[][] states,  int[] colors) {
            super();
            drawable.mutate();
            this.states = states;
            this.colors = colors;
            for (int i = 0; i < states.length; i++) {
                addState(states[i], drawable);
            }
        }
    
        @Override
        protected boolean onStateChange(int[] states) {
            if (this.states != null) {
                for (int i = 0; i < this.states.length; i++) {
                        if (StateSet.stateSetMatches(this.states[i], states)) {
                            super.setColorFilter(this.colors[i], PorterDuff.Mode.MULTIPLY);
                            return super.onStateChange(states);
                        }
                }
                super.clearColorFilter();
            }
            return super.onStateChange(states);
        }
    
        @Override
        public boolean isStateful() {
            return true;
        }
    }
    

提交回复
热议问题