Created
August 13, 2019 16:51
-
-
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.
This file contains 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.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) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
What's the point off fallback to normal methods if value wasn't found?