Last active
September 16, 2017 09:54
-
-
Save TakuSemba/8b8db8ebc79dc6f70a5e26beedae4a25 to your computer and use it in GitHub Desktop.
Spring Animation
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
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