1. 程式人生 > >Android在程式碼裡動態設定文字顏色Seletor中getColor與getColorStateList方法的區別(坑)

Android在程式碼裡動態設定文字顏色Seletor中getColor與getColorStateList方法的區別(坑)

當我們需要動態的在程式碼裡給文字設定顏色,而這個文字具有點選態的時候,我們經常會遇到怎麼設定都不好使的情況,接下來從踩坑、填坑,到最後分析原因整個流程詳細介紹一下這種case。

下面是我們在/res/color資料夾裡給元素設定的文字顏色seletor:***_view_btn_text_color_selector.xml

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:color
="@color/***_view_btn_text_color_pressed" android:state_pressed="true" />
<item android:color="@color/***_view_btn_text_color_normal" /> </selector>
1.踩坑

在程式碼裡設定元素的顏色seletor,以為在程式碼裡直接呼叫 .setTextColor(int colorValue)就可以了,結果執行效果是隻能讀取到沒獲取焦點時的色值,而其他狀態獲取不到。

//設定元素文字顏色
empty_btn?.setTextColor
(resources.getColor(R.color.***_view_btn_text_color_selector))
2.填坑

採用

empty_btn?.setTextColor(resources.getColorStateList(R.color.***_view_btn_text_color_selector))

為元素設定文字顏色;區別在於:改之前用的是getColor()方法,改之後用的是getColorStateList()方法。

3.原因分析

文字顏色的seletor在程式碼裡的顯示形式是ColorStateList,而res/color放的就是ColorStateList資源XML檔案,getColor()只能讀取單個的color。