Android Java 動態(tài)修改 CheckBox 樣式

??????小菜一直在處理動態(tài)配置頁面顏色方面的工作庐船,包括各布局,各控件等榄棵,而小菜卻在最常用最基本的 CheckBox 選項(xiàng)框這個(gè)控件卻栽了跟頭敲长,折騰了好久,今天有機(jī)會總結(jié)整理一下秉继。
??????大家都很熟悉祈噪,xml 在很多時(shí)候大大節(jié)省了我們的開發(fā)時(shí)間,但 xml 里面配置的樣式只有默認(rèn)的尚辑,在動態(tài)修改方面還是要靠 Java/Kotlin 代碼優(yōu)化辑鲤。基本上 xml 中可以配置的屬性在 Java/Kotlin 代碼中都有相對應(yīng)的方法杠茬,然而小菜在對應(yīng)使用 CheckBox 控件的 android:buttonTint="@color/colorAccent" 屬性時(shí)月褥,卻不盡如人意弛随,不僅在設(shè)置過程中需要版本大于21,更重要的是設(shè)置完之后并不起效果宁赤。小菜也查閱了不少資料舀透,請教了幾位大神,依舊沒有解決問題决左。
??????實(shí)在沒辦法懊缺,小菜決定放棄 CheckBox 轉(zhuǎn)投 v7 包中的 AppCompatCheckBox暂刘,通過設(shè)置 setSupportButtonTintList 方法來動態(tài)修改選項(xiàng)框顏色。

測試效果圖.jpg


小菜的步驟如下:

  1. 設(shè)置兩個(gè)默認(rèn)的 CheckBox 選中/未選中 狀態(tài)作為參照,如圖中第一行号坡;
  2. 設(shè)置兩個(gè) AppCompatCheckBox 默認(rèn)通過設(shè)置 style.xml 主題色配置吨凑,可實(shí)現(xiàn)與 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. 設(shè)置兩個(gè) AppCompatCheckBox 在 Java/Kotlin 代碼中設(shè)置 setSupportButtonTintList 方法婴渡,但是在未選中狀態(tài)下幻锁,選擇框依舊是配置的主題色,與 CheckBox 默認(rèn)的灰色不一致边臼,如圖中第三行越败,仍需優(yōu)化;
accb.setSupportButtonTintList(ColorStateList.valueOf(getResources().getColor(R.color.colorAccent)));
  1. 設(shè)置兩個(gè) AppCompatCheckBox 在 Java/Kotlin 代碼中不僅設(shè)置 setSupportButtonTintList 方法硼瓣,且監(jiān)聽 CompoundButton.OnCheckedChangeListener 方法究飞,再監(jiān)聽選中和未選中狀態(tài)中對選項(xiàng)框顏色做處理。
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 均設(shè)置樣式堂鲤,以 Java/Kotlin 代碼樣式為主亿傅。
Tips2: 在設(shè)置 setSupportButtonTintList 方法時(shí),初始狀態(tài)為選中時(shí)瘟栖,顏色列表第一個(gè)應(yīng)為配置的顏色值葵擎;若為未選中時(shí),顏色列表第一個(gè)應(yīng)為默認(rèn)系統(tǒng)灰色半哟。

// 工具類 繪制不同狀態(tài)的顏色
public class BitmapUtil {
    /**
     * 對TextView設(shè)置不同狀態(tài)時(shí)其文字顏色
     * @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 動態(tài)修改 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="系統(tǒng)默認(rèn) 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="默認(rèn)已選中" />

        <CheckBox
            android:id="@+id/cb2"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:checked="false"
            android:text="默認(rèn)未選中" />
    </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="默認(rèn)已選中"
            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="默認(rèn)未選中"
            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="但未選中狀態(tài)中與系統(tǒng)灰色不一致,需修改" />

    <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="默認(rèn)已選中"
            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="默認(rèn)未選中"
            android:theme="@style/MyCheckBox" />

    </LinearLayout>

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:paddingLeft="12dp"
        android:paddingTop="12dp"
        android:text="與系統(tǒng)默認(rèn)的 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="默認(rèn)已選中" />

        <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="默認(rèn)未選中" />

    </LinearLayout>
</LinearLayout>

來源: 阿策小和尚

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末寓涨,一起剝皮案震驚了整個(gè)濱河市盯串,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌戒良,老刑警劉巖体捏,帶你破解...
    沈念sama閱讀 218,284評論 6 506
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異,居然都是意外死亡几缭,警方通過查閱死者的電腦和手機(jī)河泳,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,115評論 3 395
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來年栓,“玉大人拆挥,你說我怎么就攤上這事∧匙ィ” “怎么了纸兔?”我有些...
    開封第一講書人閱讀 164,614評論 0 354
  • 文/不壞的土叔 我叫張陵,是天一觀的道長搪缨。 經(jīng)常有香客問我食拜,道長鸵熟,這世上最難降的妖魔是什么副编? 我笑而不...
    開封第一講書人閱讀 58,671評論 1 293
  • 正文 為了忘掉前任,我火速辦了婚禮流强,結(jié)果婚禮上痹届,老公的妹妹穿的比我還像新娘。我一直安慰自己打月,他們只是感情好队腐,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,699評論 6 392
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著奏篙,像睡著了一般柴淘。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上秘通,一...
    開封第一講書人閱讀 51,562評論 1 305
  • 那天为严,我揣著相機(jī)與錄音,去河邊找鬼肺稀。 笑死第股,一個(gè)胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的话原。 我是一名探鬼主播夕吻,決...
    沈念sama閱讀 40,309評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼繁仁!你這毒婦竟也來了涉馅?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 39,223評論 0 276
  • 序言:老撾萬榮一對情侶失蹤黄虱,失蹤者是張志新(化名)和其女友劉穎控漠,沒想到半個(gè)月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 45,668評論 1 314
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡盐捷,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,859評論 3 336
  • 正文 我和宋清朗相戀三年偶翅,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片碉渡。...
    茶點(diǎn)故事閱讀 39,981評論 1 348
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡聚谁,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出滞诺,到底是詐尸還是另有隱情形导,我是刑警寧澤,帶...
    沈念sama閱讀 35,705評論 5 347
  • 正文 年R本政府宣布习霹,位于F島的核電站朵耕,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏淋叶。R本人自食惡果不足惜阎曹,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,310評論 3 330
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望煞檩。 院中可真熱鬧处嫌,春花似錦、人聲如沸斟湃。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,904評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽凝赛。三九已至注暗,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間墓猎,已是汗流浹背捆昏。 一陣腳步聲響...
    開封第一講書人閱讀 33,023評論 1 270
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留陶衅,地道東北人屡立。 一個(gè)月前我還...
    沈念sama閱讀 48,146評論 3 370
  • 正文 我出身青樓,卻偏偏與公主長得像搀军,于是被迫代替她去往敵國和親膨俐。 傳聞我的和親對象是個(gè)殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,933評論 2 355

推薦閱讀更多精彩內(nèi)容

  • Android 自定義View的各種姿勢1 Activity的顯示之ViewRootImpl詳解 Activity...
    passiontim閱讀 172,139評論 25 707
  • ¥開啟¥ 【iAPP實(shí)現(xiàn)進(jìn)入界面執(zhí)行逐一顯】 〖2017-08-25 15:22:14〗 《//首先開一個(gè)線程罩句,因...
    小菜c閱讀 6,419評論 0 17
  • 沒有不作的人生 沒有不鬧的生命 緩緩逝去的歲月 流落在今朝的余暉 你看著我 奇葩的無與倫比 可那又怎樣 我看你也是...
    雨在June閱讀 189評論 0 0
  • 第十四章 蜘蛛為什么能鉆進(jìn)冰里去呀焚刺! (前情回顧:www.reibang.com/p/8f195ac0755a) ...
    _響君閱讀 263評論 0 1
  • 創(chuàng)建型模式 創(chuàng)建型模式有以下幾種:Creational Patterns: Pattern ...
    英武閱讀 682評論 0 49