Skip to content

Instantly share code, notes, and snippets.

@dzolnai
Created December 28, 2020 15:09
Show Gist options
  • Save dzolnai/b46ca1ad10d547d3ff08283173e5e5c5 to your computer and use it in GitHub Desktop.
Save dzolnai/b46ca1ad10d547d3ff08283173e5e5c5 to your computer and use it in GitHub Desktop.
Detect appbar offset
binding.appBar.addOnOffsetChangedListener(AppBarLayout.OnOffsetChangedListener { _, verticalOffset ->
// By updating the LayoutParams, we trigger the offset change listener, which then results in a somewhat infinite loop.
// This flag makes sure that we discard the next callback after updating the layout.
if (verticalOffset == lastOffset) {
return@OnOffsetChangedListener
}
val offsetPercentage = verticalOffset / -maxOffset // 0 is fully expanded, 1 is fully collapsed
val interpolatedPercentage = interpolator.getInterpolation(offsetPercentage)
val baseWidth = expandedTextWidth - (expandedTextWidth - collapsedTextWidth) * interpolatedPercentage
val marginExtra = expandedMargin - (expandedMargin - collapsedMargin) * offsetPercentage
val fullWidth = baseWidth + marginExtra + extraWidth
lastOffset = verticalOffset
binding.clickableLayout.updateLayoutParams<CollapsingToolbarLayout.LayoutParams> {
width = fullWidth.toInt()
}
binding.clickableLayout.updatePadding(bottom = ((expandedBottomPadding - (expandedBottomPadding - collapsedBottomPadding) * offsetPercentage).toInt()))
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment