Skip to content

Instantly share code, notes, and snippets.

@madsunrise
Created April 15, 2020 11:18
Show Gist options
  • Save madsunrise/1ab92ce07dcbac5e95d85b436e52d17c to your computer and use it in GitHub Desktop.
Save madsunrise/1ab92ce07dcbac5e95d85b436e52d17c to your computer and use it in GitHub Desktop.
object InsetsUtils {
fun View.doOnApplyWindowInsets(block: (View, WindowInsetsCompat, Rect) -> WindowInsetsCompat) {
val initialPadding = getCurrentPadding(this)
ViewCompat.setOnApplyWindowInsetsListener(this) { v, insets ->
block(v, insets, initialPadding)
}
requestApplyInsetsWhenAttached()
}
private fun View.requestApplyInsetsWhenAttached() {
if (isAttachedToWindow) {
requestApplyInsets()
} else {
addOnAttachStateChangeListener(object : View.OnAttachStateChangeListener {
override fun onViewDetachedFromWindow(v: View) {
v.removeOnAttachStateChangeListener(this)
v.requestApplyInsets()
}
override fun onViewAttachedToWindow(v: View?) {
}
})
}
}
private fun getCurrentPadding(view: View): Rect {
return Rect(view.paddingLeft, view.paddingTop, view.paddingRight, view.paddingBottom)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment