Skip to content

Instantly share code, notes, and snippets.

@justasm
Last active November 4, 2017 00:28
Show Gist options
  • Save justasm/ecb587ea45d56e254c078059bbc8ed26 to your computer and use it in GitHub Desktop.
Save justasm/ecb587ea45d56e254c078059bbc8ed26 to your computer and use it in GitHub Desktop.
Android View Kotlin extension for a one-shot callback after layout
fun View.afterLayout(block: View.() -> Unit) {
val originalVto = viewTreeObserver
originalVto.addOnPreDrawListener(object : ViewTreeObserver.OnPreDrawListener {
override fun onPreDraw(): Boolean {
if (originalVto.isAlive) originalVto.removeOnPreDrawListener(this)
viewTreeObserver.removeOnPreDrawListener(this)
block(this@afterLayout)
return true
}
})
}
// usage
image_view.afterLayout { Log.d("demo", "image width $width height $height") }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment