Android Color State List Resources
A ColorStateList is an XML-definable resource that acts as a dynamic color, changing based on the state of the Android View it’s applied to. For example, a button widget can be pressed, focused, or idle, and a color state list lets you assign distinct colors to each state.
These state-based colors are defined inside a single <selector> root elemant in an XML file. Each color uses an <item> tag, with attributes describing the conditions for its application. The system checks these items top-to-bottom whenever the view’s state changes, selecting the first item that meets all minimum matching state requirements (not the best overall match).
File Location & Resource Details
- Storage Path:
res/color/filename.xml(filename becomes the resource ID) - Compiled Type: Resource pointer to a
ColorStateListinstance - Resource References:
- Java/Kotlin:
R.color.filename - XML:
@[package:]color/filename
- Java/Kotlin:
XML Syntax
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:color="hex_color"
android:state_pressed=["true" | "false"]
android:state_focused=["true" | "false"]
android:state_selected=["true" | "false"]
android:state_checkable=["true" | "false"]
android:state_checked=["true" | "false"]
android:state_enabled=["true" | "false"]
android:state_window_focused=["true" | "false"] />
</selector>
Key Elements
<selector>: Root element. Contains one or more<item>tags.- Mandatory Attribute:
xmlns:android(must behttp://schemas.android.com/apk/res/android)
- Mandatory Attribute:
<item>: State-based color definition (child of<selector>).- Mandatory Attribute:
android:color(hexadecimal color value starting with #, formats include RGB, ARGB, RRGGBB, AARRGGBB) - Optional State Attributes:
state_pressed: Applies when the view is pressed (e.g., button tapped)state_focused: Applies when the view is focused (e.g., button highlighted via trackball)state_selected: Applies when the view is selected (e.g., active tab)state_checkable: Applies when the view can be checked/uncheckedstate_checked: Applies when the view is checked (e.g., checked checkbox)state_enabled: Applies when the view can receive inputstate_window_focused: Applies when the app window has focus (foreground state)
- Mandatory Attribute:
Example
-
Create the Color State List File: Save as
res/color/btn_text_color.xml<?xml version="1.0" encoding="utf-8"?> <selector xmlns:android="http://schemas.android.com/apk/res/android"> <item android:state_pressed="true" android:color="#ffff0000" /> <!-- Pressed state (red) --> <item android:state_focused="true" android:color="#ff0000ff" /> <!-- Focused state (blue) --> <item android:color="#ff000000" /> <!-- Default state (black) --> </selector> -
Apply to a View: Use
@color/btn_text_colorin your layout<Button android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Click Me" android:textColor="@color/btn_text_color" />