Skip to content

Instantly share code, notes, and snippets.

@taylorsloan
Last active November 15, 2017 19:25
Show Gist options
  • Save taylorsloan/f927c4f70c2a1b7bd8aba7dad52090ee to your computer and use it in GitHub Desktop.
Save taylorsloan/f927c4f70c2a1b7bd8aba7dad52090ee to your computer and use it in GitHub Desktop.
import android.animation.ObjectAnimator
import android.view.View
/**
* Simple class used to pulse a view infinitely then fade in when stopped.
* Created by tsloan on 11/15/2017.
*/
class PulseAnimation(view: View) {
private var pulseAnimation : ObjectAnimator? = null
private var view : View? = null
init {
this.view = view
}
/**
* Starts the pulsing animation
* @param initialAlpha Initial alpha value of the view (default: 100%)
* @param endAlpha End alpha value of the view (default: 30%)
* @param duration How long the pulse cycle is going to take (default: 400 ms)
*/
fun startAnimation(initialAlpha : Float = 1.0f, endAlpha: Float = 0.3f, duration: Long = 400) {
view?.let {
pulseAnimation = ObjectAnimator.ofFloat(it, "alpha", initialAlpha, endAlpha)
pulseAnimation?.duration = duration
pulseAnimation?.repeatCount = ObjectAnimator.INFINITE
pulseAnimation?.repeatMode = ObjectAnimator.REVERSE
pulseAnimation?.start()
}
}
/**
* Stops the animation and fades-in the view for a smooth transition.
* @param initialAlpha Initial alpha value of the view (default: 30%)
* @param endAlpha End alpha value of the view (default: 100%)
* @param duration How long the fade-in is going to take (default: 400 ms)
*/
fun stopAnimation(initialAlpha : Float = 0.3f, endAlpha: Float = 1.0f, duration: Long = 400) {
view?.let {
pulseAnimation?.end()
val fadeInAnim = ObjectAnimator.ofFloat(it, "alpha", initialAlpha, endAlpha)
fadeInAnim.duration = duration
fadeInAnim.start()
}
}
/**
* Releases UI components to prevent memory leaks
*/
fun release() {
pulseAnimation?.cancel()
view = null
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment