Skip to content

Instantly share code, notes, and snippets.

@alexjlockwood
Created August 13, 2019 16:51
Show Gist options
  • Star 10 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save alexjlockwood/19b4b7fd78f1f6f996315d820a5a908d to your computer and use it in GitHub Desktop.
Save alexjlockwood/19b4b7fd78f1f6f996315d820a5a908d to your computer and use it in GitHub Desktop.
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
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