Created
August 3, 2021 14:00
-
-
Save mattmook/b140ab90fe284292a78590896cf322d2 to your computer and use it in GitHub Desktop.
This file contains hidden or 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 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