Skip to content

Instantly share code, notes, and snippets.

@dzungvu
Created June 15, 2021 08:05
Show Gist options
  • Save dzungvu/4de15617615c33cfe0bd74cab420a38a to your computer and use it in GitHub Desktop.
Save dzungvu/4de15617615c33cfe0bd74cab420a38a to your computer and use it in GitHub Desktop.
interface TraverseLayoutInterceptor<T : View> {
fun interceptAttrs(view: T, attrs: AttributeSet)
}
inline fun <reified T : View> interceptor(
crossinline block: (view: T, attrs: AttributeSet) -> Unit
): Pair<Class<T>, TraverseLayoutInterceptor<T>> =
T::class.java to object : TraverseLayoutInterceptor<T> {
override fun interceptAttrs(view: T, attrs: AttributeSet) = block(view, attrs)
}
fun toolbarInterceptor() = interceptor<Toolbar> { view, attrs ->
for (index in 0 until attrs.attributeCount) {
attrs.getAttributeName(index)?.run {
Log.d("textViewInterceptor", "Index: $index: $this")
when (this) {
"title" -> {
attrs.getAttributeResourceValue(index, -1).takeIf { it > -1 }?.run {
view.title = view.context.getString(this)
}
}
else -> {
// Do nothing
}
}
}
}
}
fun textViewInterceptor() = interceptor<TextView> { view, attrs ->
for (index in 0 until attrs.attributeCount) {
attrs.getAttributeName(index)?.run {
Log.d("textViewInterceptor", "Index: $index: $this")
when (this) {
"text" -> {
attrs.getAttributeResourceValue(index, -1).takeIf { it > -1 }?.run {
view.text = view.context.getString(this)
}
}
"hint" -> {
attrs.getAttributeResourceValue(index, -1).takeIf { it > -1 }?.run {
view.hint = view.context.getString(this)
}
}
else -> {
// Do nothing
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment