Skip to content

Instantly share code, notes, and snippets.

@programmerr47
Created May 28, 2020 06:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save programmerr47/58dd445ea93bedc6eed444a3af2f1400 to your computer and use it in GitHub Desktop.
Save programmerr47/58dd445ea93bedc6eed444a3af2f1400 to your computer and use it in GitHub Desktop.
@SuppressWarnings("Recycle")
@UseExperimental(ExperimentalContracts::class)
inline fun AttributeSet.parseAttrs(context: Context, @StyleableRes attrs: IntArray, parser: TypedArray.() -> Unit) {
contract { callsInPlace(parser, InvocationKind.EXACTLY_ONCE) }
context.obtainStyledAttributes(this, attrs).use(parser)
}
@UseExperimental(ExperimentalContracts::class)
inline fun TypedArray.use(block: TypedArray.() -> Unit) {
contract { callsInPlace(block, InvocationKind.EXACTLY_ONCE) }
try {
block()
} finally {
recycle()
}
}
fun TypedArray.getResString(ctx: Context, index: Int): String? {
return if (hasValue(index)) {
getResourceId(index)?.let { ctx.getString(it) }
} else {
null
}
}
fun TypedArray.getResourceId(index: Int): Int? = getResourceId(index, 0).takeIf { it > 0 }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment