Android Ball Bounce Animation
This is Part II of Learning Android Series.
This tutorial will show you how to make a ball bounce animation using ObjectAnimator.
ObjectAnimator is a subclass of Value Animator, It provides support for animating properties on target objects
We will use the CustomView we created in previous tutorial but you can use any view to apply this animation.
Generate Animation Path
Our animation will use a Path which will, which will be followed in the animation, So our first step is to generate a path.
private fun generatePath(path: Path, maxh: Float, damp: Float) {
var damp1 = damp
path.lineTo(0f, maxh)
for (i in 1..8) {
path.lineTo(0f, maxh - maxh / damp1)
path.lineTo(0f, maxh)
damp1 *= 2f
}
}
This function will take an empty path
object, maxh
is height of the screen in px, and damp
is damp factor by which the height of ball bounce will decrease and will generate a bounce path.
On every loop we add the new height and the ball rest point (i.e. bottom of screen), Choose the damp factor and number of times loop run according to your need.
We can use DisplayMetrics
to get height or can use height of root container which is frame_layout
in our case.
circle_btn.setOnClickListener {
generatePath(path, frame_layout.height.toFloat() - 2 * Constants.circleRadius, damp)
ObjectAnimator.ofFloat(
it,
View.X, View.Y, path
).apply {
duration = 5000
start()
}
}
ObjectAnimator.ofFloat takes 4 arguments
public static ObjectAnimator ofFloat (Object target,
String xPropertyName,
String yPropertyName,
Path path)
Parameters:
target (Object)
: The object whose properties are to be animated. This object should have public methods on it called setNameX()
and setNameY
, where nameX
and nameY
are the value of the xPropertyName
and yPropertyName
parameters, respectively.
xPropertyName (String)
: The name of the property for the x coordinate being animated.
yPropertyName (String)
: The name of the property for the y coordinate being animated.
path (Path)
: The Path
to animate values along.
Now as soon as we click on the View the bounce animation will start playing.
Stay Safe, Stay Cool 😎