Last active
January 30, 2020 08:36
-
-
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).
This file contains 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
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