Android Java 动态修改 CheckBox 样式

      小菜一直在处理动态配置页面颜色方面的工作,包括各布局,各控件等,而小菜却在最常用最基本的 CheckBox 选项框这个控件却栽了跟头,折腾了好久,今天有机会总结整理一下。
      大家都很熟悉,xml 在很多时候大大节省了我们的开发时间,但 xml 里面配置的样式只有默认的,在动态修改方面还是要靠 Java/Kotlin 代码优化。基本上 xml 中可以配置的属性在 Java/Kotlin 代码中都有相对应的方法,然而小菜在对应使用 CheckBox 控件的 android:buttonTint="@color/colorAccent" 属性时,却不尽如人意,不仅在设置过程中需要版本大于21,更重要的是设置完之后并不起效果。小菜也查阅了不少资料,请教了几位大神,依旧没有解决问题。
      实在没办法,小菜决定放弃 CheckBox 转投 v7 包中的 AppCompatCheckBox,通过设置 setSupportButtonTintList 方法来动态修改选项框颜色。

测试效果图.jpg


小菜的步骤如下:

  1. 设置两个默认的 CheckBox 选中/未选中 状态作为参照,如图中第一行;
  2. 设置两个 AppCompatCheckBox 默认通过设置 style.xml 主题色配置,可实现与 CheckBox 效果一致,如图中第二行,但并非小菜想要的方式;
<style name="MyCheckBox" parent="Theme.AppCompat.Light">
    <item name="colorControlNormal">@color/avoscloud_feedback_text_gray</item>
    <item name="colorControlActivated">@color/colorPrimary</item>
</style>

<style name="MyCheckBox2" parent="Theme.AppCompat.Light">
    <item name="colorControlNormal">@color/avoscloud_feedback_text_gray</item>
    <item name="colorControlActivated">@color/colorPrimaryDark</item>
</style>
  1. 设置两个 AppCompatCheckBox 在 Java/Kotlin 代码中设置 setSupportButtonTintList 方法,但是在未选中状态下,选择框依旧是配置的主题色,与 CheckBox 默认的灰色不一致,如图中第三行,仍需优化;
accb.setSupportButtonTintList(ColorStateList.valueOf(getResources().getColor(R.color.colorAccent)));
  1. 设置两个 AppCompatCheckBox 在 Java/Kotlin 代码中不仅设置 setSupportButtonTintList 方法,且监听 CompoundButton.OnCheckedChangeListener 方法,再监听选中和未选中状态中对选项框颜色做处理。
accb.setSupportButtonTintList(BitmapUtil.createColorStateList(Color.GRAY, Color.RED, Color.RED,Color.RED));
accb.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
    @Override
    public void onCheckedChanged(CompoundButton compoundButton, boolean b)
    {
        if(b){
            accb.setSupportButtonTintList(BitmapUtil.createColorStateList(Color.RED, Color.RED, Color.RED,Color.RED));
        }else{
            accb.setSupportButtonTintList(BitmapUtil.createColorStateList(Color.GRAY, Color.RED, Color.RED,Color.RED));
        }
    }
});

Tips1: 若 Java/Kotlin 代码与 style.xml 均设置样式,以 Java/Kotlin 代码样式为主。
Tips2: 在设置 setSupportButtonTintList 方法时,初始状态为选中时,颜色列表第一个应为配置的颜色值;若为未选中时,颜色列表第一个应为默认系统灰色。

// 工具类 绘制不同状态的颜色
public class BitmapUtil {
    /**
     * 对TextView设置不同状态时其文字颜色
     * @param normal
     * @param pressed
     * @param focused
     * @param unable
     * @return
     */
    public static ColorStateList createColorStateList(int normal, int pressed, int focused, int unable) {
        int[] colors = new int[] { pressed, focused, normal, focused, unable, normal };
        int[][] states = new int[6][];
        states[0] = new int[] { android.R.attr.state_pressed, android.R.attr.state_enabled };
        states[1] = new int[] { android.R.attr.state_enabled, android.R.attr.state_focused };
        states[2] = new int[] { android.R.attr.state_enabled };
        states[3] = new int[] { android.R.attr.state_focused };
        states[4] = new int[] { android.R.attr.state_window_focused };
        states[5] = new int[] {};
        ColorStateList colorList = new ColorStateList(states, colors);
        return colorList;
    }
}
// Java 对 AppCompatCheckBox 绘制颜色
public class CheckBoxActivity extends AppCompatActivity {

    AppCompatCheckBox accb1, accb2, accb3, accb4, accb5, accb6;
    TextView mTitleTv;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_checkbox);

        mTitleTv = (TextView) this.findViewById(R.id.tv_toolbar_title);
        mTitleTv.setText("Java 动态修改 CheckBox 颜色");
        accb1 = (AppCompatCheckBox) this.findViewById(R.id.accb1);
        accb2 = (AppCompatCheckBox) this.findViewById(R.id.accb2);
        accb3 = (AppCompatCheckBox) this.findViewById(R.id.accb3);
        accb4 = (AppCompatCheckBox) this.findViewById(R.id.accb4);
        accb5 = (AppCompatCheckBox) this.findViewById(R.id.accb5);
        accb6 = (AppCompatCheckBox) this.findViewById(R.id.accb6);

        accb3.setSupportButtonTintList(ColorStateList.valueOf(getResources().getColor(R.color.colorAccent)));
        accb4.setSupportButtonTintList(ColorStateList.valueOf(Color.GREEN));

        accb5.setSupportButtonTintList(BitmapUtil.createColorStateList(getResources().getColor(R.color.colorAccent), getResources().getColor(R.color.colorAccent), getResources().getColor(R.color.colorAccent), getResources().getColor(R.color.colorAccent)));
        accb5.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                if (b) {
                    accb5.setSupportButtonTintList(BitmapUtil.createColorStateList(getResources().getColor(R.color.colorAccent), getResources().getColor(R.color.colorAccent), getResources().getColor(R.color.colorAccent), getResources().getColor(R.color.colorAccent)));
                } else {
                    accb5.setSupportButtonTintList(BitmapUtil.createColorStateList(Color.GRAY, getResources().getColor(R.color.colorAccent), getResources().getColor(R.color.colorAccent), getResources().getColor(R.color.colorAccent)));
                }
            }
        });
        accb6.setSupportButtonTintList(BitmapUtil.createColorStateList(Color.GRAY, Color.GREEN, Color.GREEN, Color.GREEN));
        accb6.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                if (b) {
                    accb6.setSupportButtonTintList(BitmapUtil.createColorStateList(Color.GREEN, Color.GREEN, Color.GREEN, Color.GREEN));
                } else {
                    accb6.setSupportButtonTintList(BitmapUtil.createColorStateList(Color.GRAY, Color.GREEN, Color.GREEN, Color.GREEN));
                }
            }
        });
    }
}
// xml 布局
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <include layout="@layout/common_title" />

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:paddingLeft="12dp"
        android:paddingTop="12dp"
        android:text="系统默认 CheckBox"
        android:textColor="@color/colorAccent" />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:padding="12dp">

        <CheckBox
            android:id="@+id/cb1"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:layout_weight="1"
            android:checked="true"
            android:text="默认已选中" />

        <CheckBox
            android:id="@+id/cb2"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:checked="false"
            android:text="默认未选中" />
    </LinearLayout>

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:paddingLeft="12dp"
        android:paddingTop="12dp"
        android:text="AppCompatCheckBox style.xml 主题色配置"
        android:textColor="@color/colorPrimary" />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:padding="12dp">

        <android.support.v7.widget.AppCompatCheckBox
            android:id="@+id/accb1"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:layout_weight="1"
            android:checked="true"
            android:text="默认已选中"
            android:theme="@style/MyCheckBox" />

        <android.support.v7.widget.AppCompatCheckBox
            android:id="@+id/accb2"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:layout_weight="1"
            android:checked="false"
            android:text="默认未选中"
            android:theme="@style/MyCheckBox2" />

    </LinearLayout>

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:paddingLeft="12dp"
        android:paddingTop="12dp"
        android:text="AppCompatCheckBox Java 代码颜色配置"
        android:textColor="@color/colorAccent" />

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:paddingLeft="12dp"
        android:paddingTop="12dp"
        android:text="但未选中状态中与系统灰色不一致,需修改" />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:padding="12dp">

        <android.support.v7.widget.AppCompatCheckBox
            android:id="@+id/accb3"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:layout_weight="1"
            android:checked="true"
            android:text="默认已选中"
            android:theme="@style/MyCheckBox" />

        <android.support.v7.widget.AppCompatCheckBox
            android:id="@+id/accb4"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:layout_weight="1"
            android:checked="false"
            android:text="默认未选中"
            android:theme="@style/MyCheckBox" />

    </LinearLayout>

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:paddingLeft="12dp"
        android:paddingTop="12dp"
        android:text="与系统默认的 CheckBox 样式基本一致" />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:padding="12dp">

        <android.support.v7.widget.AppCompatCheckBox
            android:id="@+id/accb5"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:layout_weight="1"
            android:checked="true"
            android:text="默认已选中" />

        <android.support.v7.widget.AppCompatCheckBox
            android:id="@+id/accb6"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:layout_weight="1"
            android:checked="false"
            android:text="默认未选中" />

    </LinearLayout>
</LinearLayout>

来源: 阿策小和尚

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 216,372评论 6 498
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 92,368评论 3 392
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 162,415评论 0 353
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,157评论 1 292
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,171评论 6 388
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,125评论 1 297
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,028评论 3 417
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 38,887评论 0 274
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,310评论 1 310
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,533评论 2 332
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,690评论 1 348
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,411评论 5 343
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,004评论 3 325
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,659评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,812评论 1 268
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 47,693评论 2 368
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,577评论 2 353

推荐阅读更多精彩内容

  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 172,071评论 25 707
  • ¥开启¥ 【iAPP实现进入界面执行逐一显】 〖2017-08-25 15:22:14〗 《//首先开一个线程,因...
    小菜c阅读 6,401评论 0 17
  • 没有不作的人生 没有不闹的生命 缓缓逝去的岁月 流落在今朝的余晖 你看着我 奇葩的无与伦比 可那又怎样 我看你也是...
    雨在June阅读 189评论 0 0
  • 第十四章 蜘蛛为什么能钻进冰里去呀! (前情回顾:www.jianshu.com/p/8f195ac0755a) ...
    _响君阅读 263评论 0 1
  • 创建型模式 创建型模式有以下几种:Creational Patterns: Pattern ...
    英武阅读 681评论 0 49