Last active
December 3, 2017 04:19
-
-
Save taylorsloan/a1ef25fd425daa8c3df52cd3c48f7b1f to your computer and use it in GitHub Desktop.
View extension functions for animating height expansion and collapse. Use these by calling "yourView.expand()" or "yourView.collapse()".
This file contains 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
import android.view.View | |
import android.view.ViewGroup | |
import android.view.animation.Animation | |
import android.view.animation.Transformation | |
/** | |
* View extensions for expanding and collapsing | |
*/ | |
fun View.expand() { | |
val widthSpec = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED) | |
val heightSpec = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED) | |
this.measure(widthSpec, heightSpec) | |
val targetHeight = this.measuredHeight | |
// Older versions of android (pre API 21) cancel animations for views with a height of 0. | |
this.layoutParams.height = 1 | |
this.visibility = View.VISIBLE | |
val a = object : Animation() { | |
override fun applyTransformation(interpolatedTime: Float, t: Transformation) { | |
this@expand.layoutParams.height = if (interpolatedTime == 1f) | |
ViewGroup.LayoutParams.WRAP_CONTENT | |
else | |
(targetHeight * interpolatedTime).toInt() + 1 // Needed for non-zero value for ConstraintLayout | |
this@expand.requestLayout() | |
} | |
override fun willChangeBounds(): Boolean { | |
return true | |
} | |
} | |
// 1dp/ms | |
a.duration = ((targetHeight / this.context.resources.displayMetrics.density).toInt()).toLong() | |
this.startAnimation(a) | |
} | |
fun View.collapse() { | |
val initialHeight = this.measuredHeight | |
val a = object : Animation() { | |
override fun applyTransformation(interpolatedTime: Float, t: Transformation) { | |
if (interpolatedTime == 1f) { | |
this@collapse.visibility = View.GONE | |
} else { | |
this@collapse.layoutParams.height = initialHeight - (initialHeight * interpolatedTime).toInt() | |
this@collapse.requestLayout() | |
} | |
} | |
override fun willChangeBounds(): Boolean { | |
return true | |
} | |
} | |
// 1dp/ms | |
a.duration = ((initialHeight / this.context.resources.displayMetrics.density).toInt()).toLong() | |
this.startAnimation(a) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment