Android 中的 getColor() 和 getColorStateList() 有什么区别

What is the different between getColor() and getColorStateList() in Android

我正在使用 getColor() 方法从资源中 select 着色。但是我发现还有一个方法叫getColorStateList()。哪个好用,它们有什么区别?

getColor() Returns 与特定资源 ID 关联的颜色整数

getColorStateList() ColorStateLists 是根据应用程序资源目录的 "color" 子目录中定义的 XML 资源文件创建的。 XML 文件包含单个 "selector" 元素,其中包含多个 "item" 元素。例如:

<selector xmlns:android="http://schemas.android.com/apk/res/android">
   <item android:state_focused="true"
           android:color="@color/sample_focused" />
   <item android:state_pressed="true"
           android:state_enabled="false"
           android:color="@color/sample_disabled_pressed" />
   <item android:state_enabled="false"
           android:color="@color/sample_disabled_not_pressed" />
   <item android:color="@color/sample_default" />
 </selector>

假设您想要 setBackgroundColor 到视图,例如 linearLayout。 如果你想让它的背景颜色永久,你会想使用getColor()来设置某种颜色。 但是如果你想让它的颜色在不同的状态和事件上改变,比如按下状态未按下状态您可能想要设置包含这些颜色更改任务代码的 xml 文件的资源 ID。

这是我在代码中所说的:

linearLayout.setBackgroundColor(getResources().getColor(R.color.red);

上面的代码行将 linearLayout 的永久颜色设置为红色。

linearLayout.setBackgroundTintList(getResources().getColorStateList(R.drawable.layout_background));

上面的这一行代码会在按下布局时将背景色设置为红色,在未按下布局时将背景色设置为白色。

layout_background.xml :

<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_pressed="true"
       android:color="@color/red" />
    <item android:state_pressed="false"
       android:color="@color/white" />
</selector>