Skip to content

Instantly share code, notes, and snippets.

@TakuSemba
Last active September 16, 2017 09:54
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 TakuSemba/8b8db8ebc79dc6f70a5e26beedae4a25 to your computer and use it in GitHub Desktop.
Save TakuSemba/8b8db8ebc79dc6f70a5e26beedae4a25 to your computer and use it in GitHub Desktop.
Spring Animation
class SpringPositionView @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0) : View(context, attrs, defStyleAttr) {
private companion object Params {
private const val STIFFNESS = SpringForce.STIFFNESS_MEDIUM
private const val DAMPING_RATIO = SpringForce.DAMPING_RATIO_HIGH_BOUNCY
}
private lateinit var xAnim: SpringAnimation
private lateinit var yAnim: SpringAnimation
init {
viewTreeObserver.addOnGlobalLayoutListener {
xAnim = SpringAnimation(this, SpringAnimation.X).apply {
spring = SpringForce(x).apply {
stiffness = STIFFNESS
dampingRatio = DAMPING_RATIO
}
}
yAnim = SpringAnimation(this, SpringAnimation.Y).apply {
spring = SpringForce(y).apply {
stiffness = STIFFNESS
dampingRatio = DAMPING_RATIO
}
}
}
var dX = 0f
var dY = 0f
setOnTouchListener { view, event ->
when (event.actionMasked) {
MotionEvent.ACTION_DOWN -> {
dX = view.x - event.rawX
dY = view.y - event.rawY
xAnim.cancel()
yAnim.cancel()
}
MotionEvent.ACTION_MOVE -> {
animate()
.x(event.rawX + dX)
.y(event.rawY + dY)
.setDuration(0)
.start()
}
MotionEvent.ACTION_UP -> {
xAnim.start()
yAnim.start()
}
}
true
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment