Skip to content

Instantly share code, notes, and snippets.

@addeeandra
Last active March 13, 2022 10:26
Show Gist options
  • Save addeeandra/d40053f2ee02d37858715f6b930c9732 to your computer and use it in GitHub Desktop.
Save addeeandra/d40053f2ee02d37858715f6b930c9732 to your computer and use it in GitHub Desktop.
Reusable ViewStubBehavior within Scrolling Layout.
import android.view.ViewStub
import android.widget.FrameLayout
import androidx.databinding.ViewStubProxy
object ViewStubBehavior {
fun setup(
stubWrapper: FrameLayout,
stubProxy: ViewStubProxy,
scrollContainer: FrameLayout,
onInflateListener: ViewStub.OnInflateListener? = null
) {
stubProxy.setOnInflateListener(onInflateListener)
scrollContainer.viewTreeObserver.addOnScrollChangedListener {
// skip if stub is already inflated
if (stubProxy.isInflated) return@addOnScrollChangedListener
val wrapperEdge = stubWrapper.top
val scrollEdge = scrollContainer.height + scrollContainer.scrollY
val diff = wrapperEdge - scrollEdge
// inflate if wrapper edge's and scroll edge's collided. Called once only.
if (diff <= 0) stubProxy.viewStub?.inflate()
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment