Skip to content

Instantly share code, notes, and snippets.

@mattmook
Created August 3, 2021 14:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mattmook/b140ab90fe284292a78590896cf322d2 to your computer and use it in GitHub Desktop.
Save mattmook/b140ab90fe284292a78590896cf322d2 to your computer and use it in GitHub Desktop.
class ShadowScrollBehavior(context: Context, attrs: AttributeSet) : AppBarLayout.ScrollingViewBehavior(context, attrs) {
@SuppressLint("PrivateResource")
private val maxElevation = context.resources.getDimensionPixelSize(R.dimen.design_appbar_elevation).toFloat()
override fun onDependentViewChanged(parent: CoordinatorLayout, child: View, dependency: View):
Boolean {
if (dependency is AppBarLayout) {
when (child) {
is NestedScrollView -> {
setElevation(child, dependency)
addScrollListener(child, dependency)
}
is RecyclerView -> {
setElevation(child, dependency)
addScrollListener(child, dependency)
}
}
}
return super.onDependentViewChanged(parent, child, dependency)
}
private fun addScrollListener(child: NestedScrollView, dependency: AppBarLayout) {
child.setOnScrollChangeListener { _: NestedScrollView?, _: Int, _: Int, _: Int, _: Int ->
setElevation(child, dependency)
}
}
private fun addScrollListener(child: RecyclerView, dependency: AppBarLayout) {
child.clearOnScrollListeners()
child.addOnScrollListener(
object : RecyclerView.OnScrollListener() {
override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
super.onScrolled(recyclerView, dx, dy)
setElevation(recyclerView, dependency)
}
}
)
}
private fun setElevation(view: View, appBarLayout: AppBarLayout) {
val elevation = if (view.canScrollVertically(SCROLL_DIRECTION_UP)) maxElevation else 0f
ViewCompat.setElevation(appBarLayout, elevation)
}
companion object {
private const val SCROLL_DIRECTION_UP = -1
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment