Created
October 20, 2022 17:05
-
-
Save Jeff-Soares/2c646155b6f35f2e43bae857d199b52b 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
fun View.expandOrCollapse(expand: Boolean) { | |
if (expand) expand() else collapse() | |
} | |
fun View.expand() { | |
val matchParentMeasureSpec = View.MeasureSpec.makeMeasureSpec((parent as View).width, View.MeasureSpec.EXACTLY) | |
val wrapContentMeasureSpec = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED) | |
measure(matchParentMeasureSpec, wrapContentMeasureSpec) | |
val targetHeight = measuredHeight | |
var actualHeight = layoutParams.height | |
if (actualHeight <= 0) { | |
actualHeight = 1 | |
layoutParams.height = 1 | |
} | |
visibility = View.VISIBLE | |
val anim = object : Animation() { | |
override fun applyTransformation(interpolatedTime: Float, t: android.view.animation.Transformation?) { | |
layoutParams.height = | |
if (interpolatedTime == 1f) ViewGroup.LayoutParams.WRAP_CONTENT | |
else actualHeight + ((targetHeight - actualHeight) * interpolatedTime).toInt() | |
requestLayout() | |
} | |
override fun willChangeBounds() = true | |
} | |
// Expansion speed of 1dp/ms | |
anim.duration = (targetHeight / context.resources.displayMetrics.density).toInt().toLong() | |
startAnimation(anim) | |
} | |
fun View.collapse() { | |
val initialHeight = measuredHeight | |
val anim = object : Animation() { | |
override fun applyTransformation(interpolatedTime: Float, t: android.view.animation.Transformation?) { | |
if (interpolatedTime == 1f) | |
visibility = View.GONE | |
else { | |
layoutParams.height = initialHeight - (initialHeight * interpolatedTime).toInt() | |
requestLayout() | |
} | |
} | |
override fun willChangeBounds() = true | |
} | |
// Collapse speed of 1dp/ms | |
anim.duration = (initialHeight / context.resources.displayMetrics.density).toInt().toLong() | |
startAnimation(anim) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment