Basically, Animation is a method in which pictures are manipulated to appear as moving images. In our use case in android, the animation is giving motion to views in order to improve user experience.
Let’s start with an example of a simple rotation animation on a view
1 |
view.animate().rotationBy(360f).setDuration(300).setInterpolator(new LinearInterpolator()).start(); |
Here, we have called the animate() function which is by default present in the View class. The above code animates the view by 360 degrees for 300 ms.
Let’s see another example of an animation where we will change the image of the view.
In the first step, we will create an animation list drawable file(rocket_thrust.xml):
1 2 3 4 5 6 |
<animation-list xmlns:android="http://schemas.android.com/apk/res/android" android:oneshot="true"> <item android:drawable="@drawable/rocket_thrust1" android:duration="200" /> <item android:drawable="@drawable/rocket_thrust2" android:duration="200" /> <item android:drawable="@drawable/rocket_thrust3" android:duration="200" /> </animation-list> |
Then on a button click, we are going to perform the animation:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
AnimationDrawable rocketAnimation; public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); ImageView rocketImage = (ImageView) findViewById(R.id.rocket_image); rocketImage.setBackgroundResource(R.drawable.rocket_thrust); rocketAnimation = (AnimationDrawable) rocketImage.getBackground(); rocketImage.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { rocketAnimation.start(); } }); } |
Here, on a button click animation gets started and works till the duration mentioned in the drawable file. In the drawable file, we have set the oneshot attribute as true this will only perform the animation only for one cycle otherwise it animates till stopped.
We can also reposition a view on the screen with the help of ObjectAnimator API. The ObjectAnimator API provides an easy way to move a view in a specified time. Below is an example of the same:
1 2 3 |
ObjectAnimator animation = ObjectAnimator.ofFloat(view, "translationX", 200f); animation.setDuration(1000); animation.start(); |
This example will move the view 200 pixels horizontally from the current location in 1 second.
In this way, we can create multiple animations in the app.
References: