Sunday, 17 May 2015

Creating bouncing ball Animation in Android

Background

In this post I am going to show a very simple animation - Bouncing a ball. As much as Animations are very cool to look at, they are tricky and must be handled carefully.

Animation coding Tip : Just a tip here. Animations are generally started in onResume() method and stopped in onPause() method. You should not do it in onCreate() and onDestroy() methods as these methods are not guaranteed to be invoked every time.

Creating the Layouts

Lets create layouts that we will need to create a animated bouncing ball. To start with lets first create our ball.

For this I am going to create an oval shape in android. This will be in ball_shape.xml file under drawable folder. Contents of it are -

As you can see we have a button and a ball (essentially ImageView with background set as oval shape) below it. Let's animate this now with our code. Layout will looks as follows -

Animating Bouncing Ball

To animate the ball we fill first set the layout of the Activity with the layout xml we have just created. Then we will get reference to our Button and ball and when user click on the button we will animate the ball so that it appears like bouncing.