Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Kotlin helper functions for extracting ColorStateLists and Drawables from a TypedArray using AppCompatResources.
import android.content.Context
import android.content.res.ColorStateList
import android.content.res.TypedArray
import android.graphics.drawable.Drawable
import androidx.annotation.StyleableRes
import androidx.appcompat.content.res.AppCompatResources
/**
* Utility methods for extracting [ColorStateList]s and [Drawable]s from a [TypedArray].
* The resources are inflated using [AppCompatResources], which provides bug fixes and backports
* features introduced on new platforms.
*/
object TypedArrayUtils {
fun getColorStateList(context: Context, typedArray: TypedArray, @StyleableRes index: Int): ColorStateList? {
if (typedArray.hasValue(index)) {
val resourceId = typedArray.getResourceId(index, 0)
if (resourceId != 0) {
val value = AppCompatResources.getColorStateList(context, resourceId)
if (value != null) {
return value
}
}
}
return typedArray.getColorStateList(index)
}
fun getDrawable(context: Context, typedArray: TypedArray, @StyleableRes index: Int): Drawable? {
if (typedArray.hasValue(index)) {
val resourceId = typedArray.getResourceId(index, 0)
if (resourceId != 0) {
val value = AppCompatResources.getDrawable(context, resourceId)
if (value != null) {
return value
}
}
}
return typedArray.getDrawable(index)
}
}
@KonstantinBerkow

This comment has been minimized.

Copy link

KonstantinBerkow commented Aug 17, 2019

What's the point off fallback to normal methods if value wasn't found?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.