• Android原生实现控件选择背景变色方案(API28及以上)


    Android控件点击/选择后控件背景变色的实现方式有很多种,例如使用selector的xml文件实现。这里介绍一下另一种Android原生的点击/选择实现方案(API28及以上),也就是ColorStateListDrawable

    ColorStateListDrawable是一个可根据不同状态显示不同颜色的Drawable。

    实现效果,选择前/选择后:
    在这里插入图片描述
    这里我们利用继承LinearLayoutCompat的方式来实现:

    属性

    创建自定义属性

        
        
            
            
            
            
            
            
            
            
        
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11

    布局

    创建布局文件

    
    
    
        
    
            
    
            
        
    
        
    
        
    
    
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    public class Chip extends LinearLayoutCompat implements Checkable {
    
        /**
         * Interface definition for a callback to be invoked when the checked state of a chip
         * changed.
         */
        public interface OnCheckedChangeListener {
            /**
             * Called when the checked state of a chip has changed.
             *
             * @param chip      The chip whose state has changed.
             * @param isChecked The new checked state of buttonView.
             */
            void onCheckedChanged(Chip chip, boolean isChecked);
        }
    
        private FrameLayout content;
        private ImageView check;
        private TextView title;
        private ImageView close;
        private OnRemoveListener onRemoveListener;
        private boolean checkedState = false;
        private OnCheckedChangeListener onCheckedChangeListener;
    
        public interface OnRemoveListener {
            void onDismiss();
        }
    
        public Chip(Context context) {
            super(context, null, R.attr.carbon_chipStyle);
            initChip(null, R.attr.carbon_chipStyle, R.style.carbon_Chip);
        }
    
        public Chip(Context context, CharSequence text) {
            super(context, null, R.attr.carbon_chipStyle);
            initChip(null, R.attr.carbon_chipStyle, R.style.carbon_Chip);
            setText(text);
        }
    
        public Chip(Context context, AttributeSet attrs) {
            super(context, attrs, R.attr.carbon_chipStyle);
            initChip(attrs, R.attr.carbon_chipStyle, R.style.carbon_Chip);
        }
    
        public Chip(Context context, AttributeSet attrs, @AttrRes int defStyleAttr) {
            super(context, attrs, defStyleAttr);
            initChip(attrs, defStyleAttr, R.style.carbon_Chip);
        }
    
        private static int[] colorStateIds = new int[]{
                R.styleable.Chip_android_background,
                R.styleable.Chip_pressed_color,
                R.styleable.Chip_checked_color,
                R.styleable.Chip_un_enable_color
        };
    
        private void initChip(AttributeSet attrs, @AttrRes int defStyleAttr, @StyleRes int defStyleRes) {
            inflate(getContext(), R.layout.carbon_chip, this);
            title = findViewById(R.id.carbon_chipText);
            content = findViewById(R.id.carbon_chipContent);
            check = findViewById(R.id.carbon_chipCheck);
            close = findViewById(R.id.carbon_chipClose);
    
            close.setOnClickListener(v -> {
                if (onRemoveListener != null)
                    onRemoveListener.onDismiss();
            });
    
            TypedArray a = getContext().obtainStyledAttributes(attrs, R.styleable.Chip, defStyleAttr, defStyleRes);
    		// 初始化背景
            Carbon.initDefaultBackground(this, a, colorStateIds);
    		// 初始化相关自定义属性
            setText(a.getString(R.styleable.Chip_android_text));
            setIcon(Carbon.getDrawable(this, a, R.styleable.Chip_carbon_icon, 0));
            setRemovable(a.getBoolean(R.styleable.Chip_carbon_removable, false));
           
            a.recycle();
        }
    
        @Deprecated
        public void setText(String text) {
            setText((CharSequence) text);
        }
    
        public void setText(CharSequence text) {
            if (text != null) {
                title.setText(text);
                title.setVisibility(View.VISIBLE);
            } else {
                title.setVisibility(View.GONE);
            }
        }
    
        public void setText(int resId) {
            setText(getResources().getString(resId));
        }
    
        public String getText() {
            return (String) title.getText();
        }
    
        public View getTitleView() {
            return title;
        }
    
        public void setIcon(int iconRes) {
            content.removeAllViews();
            if (iconRes == 0) {
                content.setVisibility(GONE);
                return;
            }
            content.setVisibility(VISIBLE);
            ImageView icon = new ImageView(getContext());
            content.addView(icon);
            icon.setImageResource(iconRes);
        }
    
        public void setIcon(Drawable drawable) {
            content.removeAllViews();
            if (drawable == null) {
                content.setVisibility(GONE);
                return;
            }
            content.setVisibility(VISIBLE);
            ImageView icon = new ImageView(getContext());
            content.addView(icon);
            icon.setImageDrawable(drawable);
        }
    
        public void setIcon(Bitmap bitmap) {
            content.removeAllViews();
            if (bitmap == null) {
                content.setVisibility(GONE);
                return;
            }
            content.setVisibility(VISIBLE);
            ImageView icon = new ImageView(getContext());
            content.addView(icon);
            icon.setImageBitmap(bitmap);
        }
    
        @Deprecated
        public Drawable getIcon() {
            if (content.getChildCount() > 0 && content.getChildAt(0) instanceof ImageView)
                return ((ImageView) content.getChildAt(0)).getDrawable();
            return null;
        }
    
        @Deprecated
        public View getIconView() {
            if (content.getChildCount() > 0 && content.getChildAt(0) instanceof ImageView)
                return content.getChildAt(0);
            return null;
        }
    
        public View getContentView() {
            if (content.getChildCount() > 0)
                return content.getChildAt(0);
            return null;
        }
    
        public void setContentView(View view) {
            content.removeAllViews();
            if (view != null) {
                content.setVisibility(VISIBLE);
                content.addView(view);
            } else {
                content.setVisibility(GONE);
            }
        }
    
        public void setRemovable(boolean removable) {
            close.setVisibility(removable ? VISIBLE : GONE);
        }
    
        public boolean isRemovable() {
            return close.getVisibility() == VISIBLE;
        }
    
        public void setOnRemoveListener(OnRemoveListener onRemoveListener) {
            this.onRemoveListener = onRemoveListener;
        }
    
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85
    • 86
    • 87
    • 88
    • 89
    • 90
    • 91
    • 92
    • 93
    • 94
    • 95
    • 96
    • 97
    • 98
    • 99
    • 100
    • 101
    • 102
    • 103
    • 104
    • 105
    • 106
    • 107
    • 108
    • 109
    • 110
    • 111
    • 112
    • 113
    • 114
    • 115
    • 116
    • 117
    • 118
    • 119
    • 120
    • 121
    • 122
    • 123
    • 124
    • 125
    • 126
    • 127
    • 128
    • 129
    • 130
    • 131
    • 132
    • 133
    • 134
    • 135
    • 136
    • 137
    • 138
    • 139
    • 140
    • 141
    • 142
    • 143
    • 144
    • 145
    • 146
    • 147
    • 148
    • 149
    • 150
    • 151
    • 152
    • 153
    • 154
    • 155
    • 156
    • 157
    • 158
    • 159
    • 160
    • 161
    • 162
    • 163
    • 164
    • 165
    • 166
    • 167
    • 168
    • 169
    • 170
    • 171
    • 172
    • 173
    • 174
    • 175
    • 176
    • 177
    • 178
    • 179
    • 180
    • 181
    • 182
    • 183
    • 184

    重点在于为控件手动设置一个ColorListDrawable充当背景图片:

    // 为控件设置一个背景图片
     public static void initDefaultBackground(View view, TypedArray a, int[] ids) {
            Drawable d = getDefaultColorDrawable(view, a, ids);
            if (d != null)
                view.setBackgroundDrawable(d);
        }
       // 根据我们提供的android:background,pressed_color,checked_color,un_enable_color的值生成一个ColorStateListDrawable
        public static Drawable getDefaultColorDrawable(View view, TypedArray a, int[] ids) {
            ColorStateList color = getDefaultColorStateList(view, a, ids);
            if (color != null) {
                Drawable d = null;
                if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.Q) {
                    d = new ColorStateListDrawable(color);
                }
                return d;
            }
            return null;
        }
    
        public static ColorStateList getDefaultColorStateList(View view, TypedArray a, int[] ids) {
            Context context = view.getContext();
            int chip_bg = ids[0];
            int chip_pressed_bg = ids[1];
            int chip_checked_bg = ids[2];
            int chip_un_enable_bg = ids[3];
    
            if (!a.hasValue(chip_bg))
                return null;
            int backgroundColor = a.getColor(chip_bg, 0);
            int pressedBgColor = a.getColor(chip_pressed_bg,ContextCompat.getColor(context, R.color.carbon_colorControlPressed));
            int checkedBgColor = a.getColor(chip_checked_bg,ContextCompat.getColor(context,R.color.carbon_colorControlActivated));
            int unEnableBgColor = a.getColor(chip_un_enable_bg,ContextCompat.getColor(context,R.color.carbon_colorControlDisabled));
    
    
            return ColorStateListFactory.getInstance().make(context,backgroundColor,
                    pressedBgColor,
                    checkedBgColor,
                    unEnableBgColor,
                    getThemeColor(context,com.google.android.material.R.attr.colorError));
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40

    ColorStateListFactory

    状态和颜色一一对应

    public ColorStateList make(Context context,int defaultColor,int pressed,int activated,int disabled,int invalid){
            return new ColorStateList(
                    new int[][]{
                        new int[]{-android.R.attr.state_enabled}, // unenable
                        new int[]{android.R.attr.state_pressed}, // pressed
                        new int[]{android.R.attr.state_checked}, //checked
                        new int[]{android.R.attr.state_activated},//activated
                        new int[]{android.R.attr.state_selected},//selected
                        new int[]{android.R.attr.state_focused},//focused
                        new int[]{}
                    },
                    new int[]{
                        disabled,
                        pressed,
                        activated,
                        activated,
                        activated,
                        activated,
                        defaultColor
                    });
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21

    这样,我们就实现了按下控件,控件的背景颜色就会改变。

    但是,LinearCompact本身是没有check状态的,因此这就需要我们为它添加check状态。

    Checkable接口

    Chip实现Checkable接口:

    public class Chip extends LinearLayoutCompat implements Checkable {
        // 定义状态集
        private static final int[] CHECKED_STATE_SET = {
                android.R.attr.state_checked
        };
        
        public interface OnCheckedChangeListener {
            /**
             * Called when the checked state of a chip has changed.
             *
             * @param chip      The chip whose state has changed.
             * @param isChecked The new checked state of buttonView.
             */
            void onCheckedChanged(Chip chip, boolean isChecked);
        }
    
    ...
    
    
    public void toggle() {
            setChecked(!isChecked());
        }
    
        @Override
        public boolean performClick() {
            toggle();
    
            if (onCheckedChangeListener != null)
                onCheckedChangeListener.onCheckedChanged(this, isChecked());
    
            final boolean handled = super.performClick();
            if (!handled) {
                // View only makes a sound effect if the onClickListener was
                // called, so we'll need to make one here instead.
                playSoundEffect(SoundEffectConstants.CLICK);
            }
    
            return handled;
        }
    
        @ViewDebug.ExportedProperty
        public boolean isChecked() {
            return checkedState;
        }
    
        /**
         * 

    Changes the checked state of this chip.

    * 第二步 * 在设置状态时却没有触发到这个状态。所以我们需要自己去触发这个check状态。 * @param checked true to check the chip, false to uncheck it */ public void setChecked(boolean checked) { if (this.checkedState != checked) { checkedState = checked; check.setVisibility(checked ? VISIBLE : GONE); // 在状态改变时,调用refreshDrawableState()刷新状态。 refreshDrawableState(); } } // 第一步,我们要把状态给加进去。我们需要重写protected int[] onCreateDrawableState(int extraSpace)方法; /** * 先调用父类的onCreateDrawableState方法得到状态数组对象drawableState,但是参数extraSpace要加上1,因为我们要往里面增加一个状态。 * 然后判断在代码逻辑中,是否为选中状态,如果是的话,调用mergeDrawableStates(drawableState, CHECKED_STATE_SET)方法把我们的状态值给加进去, * 最终返回drawableState。 * @param extraSpace if non-zero, this is the number of extra entries you * would like in the returned array in which you can place your own * states. * * @return */ @Override protected int[] onCreateDrawableState(int extraSpace) { final int[] drawableState = super.onCreateDrawableState(extraSpace + 1); if (isChecked()) { mergeDrawableStates(drawableState, CHECKED_STATE_SET); } return drawableState; } /** * Register a callback to be invoked when the checked state of this chip changes. * * @param listener the callback to call on checked state change */ public void setOnCheckedChangeListener(OnCheckedChangeListener listener) { onCheckedChangeListener = listener; } }
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85
    • 86
    • 87
    • 88
    • 89
    • 90
    • 91
    • 92

    怎么使用

    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11

    完整代码可查看:
    Chip部分

  • 相关阅读:
    DGIOT边缘主机-Linux版操作手册
    FFmepg使用指南
    Qml-跨窗口拖动图片、物体
    用 JHipster Azure Spring Apps 构建和部署 Spring 应用
    2021 XV6 5:Copy-on-Write Fork
    Java实现二叉树两个节点最近公共祖先
    17-CSS3过渡
    Mac 安装 boost(bjam)
    Zemax基础知识6--设计小知识
    ES6(二)
  • 原文地址:https://blog.csdn.net/jxq1994/article/details/133706635