Skip to content

Instantly share code, notes, and snippets.

@kakajika
Last active January 30, 2020 08:36
Show Gist options
  • Save kakajika/8bcddeff2816bf2069ccb033a8ce03b6 to your computer and use it in GitHub Desktop.
Save kakajika/8bcddeff2816bf2069ccb033a8ce03b6 to your computer and use it in GitHub Desktop.
Listener for View's global layout event only once like [OneShotPreDrawListener](https://developer.android.com/reference/androidx/core/view/OneShotPreDrawListener).
class OneShotGlobalLayoutListener private constructor(
private val view: View,
private val runnable: Runnable
) : ViewTreeObserver.OnGlobalLayoutListener, View.OnAttachStateChangeListener {
private var viewTreeObserver: ViewTreeObserver = view.viewTreeObserver
init {
view.viewTreeObserver.addOnGlobalLayoutListener(this)
view.addOnAttachStateChangeListener(this)
}
override fun onGlobalLayout() {
removeListener()
runnable.run()
}
fun removeListener() {
if (viewTreeObserver.isAlive) {
viewTreeObserver.removeOnGlobalLayoutListener(this)
} else {
view.viewTreeObserver.removeOnGlobalLayoutListener(this)
}
view.removeOnAttachStateChangeListener(this)
}
override fun onViewAttachedToWindow(v: View) {
viewTreeObserver = v.viewTreeObserver
}
override fun onViewDetachedFromWindow(v: View) {
removeListener()
}
companion object {
fun add(view: View, runnable: Runnable): OneShotGlobalLayoutListener {
return OneShotGlobalLayoutListener(view, runnable)
}
fun add(view: View, runnable: () -> Unit): OneShotGlobalLayoutListener {
return OneShotGlobalLayoutListener(view, Runnable(runnable))
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment