Last active
July 3, 2025 12:46
-
-
Save LouisCAD/1419671450e213092f94d73a719cc82e to your computer and use it in GitHub Desktop.
Kotlin DSL for Android's ColorStateList
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import android.content.res.ColorStateList | |
import android.util.StateSet | |
import androidx.annotation.AttrRes | |
import androidx.annotation.ColorInt | |
/** | |
* **IMPORTANT**: Make sure to not use `android.R.attr.enabled` or friends, | |
* but the `state_` prefixed attributes, like `android.R.attr.state_enabled`. | |
* | |
* Here are all the supported state attributes: | |
* [android.R.attr.state_window_focused] | |
* [android.R.attr.state_selected] | |
* [android.R.attr.state_focused] | |
* [android.R.attr.state_enabled] | |
* [android.R.attr.state_pressed] | |
* [android.R.attr.state_activated] | |
* [android.R.attr.state_accelerated] | |
* [android.R.attr.state_hovered] | |
* [android.R.attr.state_drag_can_accept] | |
* [android.R.attr.state_drag_hovered] | |
* [android.R.attr.state_checked] | |
* | |
* Example usage: | |
* ```kotlin | |
* someView.backgroundTintList = colorStateList { | |
* addForState(android.R.attr.state_enabled, someColor) | |
* addForRemainingStates(disabledColor) | |
* } | |
* ``` | |
*/ | |
inline fun colorStateList(block: ColorStateListBuilder.() -> Unit): ColorStateList { | |
return ColorStateListBuilder().apply(block).build() | |
} | |
class ColorStateListBuilder @PublishedApi internal constructor() { | |
fun addForStates( | |
@AttrRes vararg stateSet: Int, | |
@ColorInt color: Int | |
) { | |
entries.add(Entry(stateSet, color)) | |
} | |
fun addForState( | |
@AttrRes state: Int, | |
@ColorInt color: Int | |
) { | |
entries.add(Entry(intArrayOf(state), color)) | |
} | |
fun addForRemainingStates(@ColorInt color: Int) { | |
entries.add(Entry(StateSet.WILD_CARD, color)) | |
} | |
@PublishedApi | |
internal fun build(): ColorStateList { | |
return ColorStateList(Array(entries.size) { i -> | |
entries[i].stateSet | |
}, IntArray(entries.size) { i -> | |
entries[i].color | |
}) | |
} | |
private class Entry( | |
@AttrRes val stateSet: IntArray, | |
@ColorInt val color: Int | |
) | |
private val entries = mutableListOf<Entry>() | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
someView.backgroundTintList = colorStateList { | |
addForState(android.R.attr.state_enabled, someColor) | |
addForRemainingStates(disabledColor) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment