Created
April 15, 2020 11:18
-
-
Save madsunrise/1ab92ce07dcbac5e95d85b436e52d17c to your computer and use it in GitHub Desktop.
This file contains hidden or 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
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