Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 63

Animation in Android with

Example + Quiz 3
Animation
• Animation is the process of adding a motion effect to any view,
image, or text. With the help of an animation, you can add motion or
can change the shape of a specific view. Animation in Android is
generally used to give your UI a rich look and feel
Types of animations
• The animations are basically of three types as follows:
1. Property Animation
2. View Animation
3. Drawable Animation
1. Property Animation
• Property Animation is one of the robust frameworks which allows
animating almost everything. This is one of the powerful and flexible
animations which was introduced in Android 3.0. Property animation
can be used to add any animation in the CheckBox, RadioButtons, and
widgets other than any view.
2. View Animation
• View Animation can be used to add animation to a specific view to
perform tweened animation (Tweened animation, also known as
"tweening," is a technique used in animation to create smooth
transitions between keyframes) on views. Tweened animation
calculates animation information such as size, rotation, start point,
and endpoint. These animations are slower and less flexible. An
example of View animation can be used if we want to expand a
specific layout in that place we can use View Animation. The example
of View Animation can be seen in Expandable RecyclerView.
3. Drawable Animation
• Drawable Animation is used if you want to animate one image over
another. The simple way to understand is to animate drawable is to
load the series of drawable one after another to create an animation.
A simple example of drawable animation can be seen in many apps
Splash screen on apps logo animation.
Important Methods of Animation

• startAnimation() This method will start the animation.


• clearAnimation() This method will clear the animation running on a
specific view.
• The animation is a method in which a collection of images is
combined in a specific way and processed then they appear as moving
images. Building animations make on-screen objects seems to be
alive. Android has quite a few tools to help you create animations
with relative ease.
XML Attribute Description
android:id Sets unique id of the view

Used to specify the duration of the


android:duration
animation
Table 2: Angular and Scale Attributes
XML Attribute Description
Starting angular position (in
android:fromDegrees
degrees)
Ending angular position (in
android:toDegrees
degrees)
android:fromXScale Starting X size offset
android:toXScale Ending X size offset
android:fromYScale Starting Y size offset
android:toYScale Ending Y size offset
Represents the X-axis coordinates
android:pivotX
to zoom from the starting point
Represents the Y-axis coordinates
android:pivotY
to zoom from the starting point
Table 3: Alpha, Delta, and Other
Attributes
XML Attribute Description
Starting alpha value for the
animation (1.0 means fully
android:fromAlpha opaque and 0.0 means fully
transparent)
android:toAlpha Ending alpha value
Change in Y coordinate to be
android:fromYDelta applied at the beginning of the
animation
Change in Y coordinate to be
android:toYDelta applied at the end of the
animation

android:interpolator It defines the rate of change of an


animation
Delay occurs when an animation
android:startOffset runs (in ms), once start time is
reached
Implementation
Step 1: Create a New Project

• To create a new project in Android Studio please refer to How to


Create/Start a New Project in Android Studio. Note that select Java as
the programming language.

Step 2: Working with the strings.xml file

• Strings.xml can be found from the app > res > values > strings.xml. Below
is the snippet for the strings.xml file.
String.xml file code
<resources>
<string name="app_name">app</string>
<string name="blink">BLINK</string>
<string name="clockwise">ROTATE</string>
<string name="fade">FADE</string>
<string name="move">MOVE</string>
<string name="slide">SLIDE</string>
<string name="zoom">ZOOM</string>
<string name="stop_animation">STOP ANIMATION</string>

</resources>
Optional (if throw error remove it)
• Step 3: Add google repository in the build.gradle file of the application project if
by default it is not there
buildscript {
repositories {
google()
mavenCentral()
}
• google(): This is a shorthand method to add Google's Maven repository. It hosts
Android libraries and tools provided by Google.
• mavenCentral(): This adds the Maven Central repository, a widely used repository
for Java and Android libraries.
Optional (if throw error remove it)
• Step 3: Add google repository in the build.gradle file of the application
project if by default it is not there
All Jetpack components are available in the Google Maven repository, include
them in the build.gradle file
allprojects {
repositories {
google()
mavenCentral()
}
}
Jetpack (often stylized as Jetpack or Android Jetpack) is a suite of
libraries, tools, and architectural guidance provided by Google to help
Android developers build robust, high-quality apps more efficiently. It is
designed to simplify complex development task
• Step 4: Working with the activity_main.xml file
• Create ImageView in the activity_main.xml along with buttons that
will add animation to the view. Navigate to the app > res > layout >
activity_main.xml. Below is the code for the activity_main.xml file.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">

<ImageView
android:id="@+id/imageview"
android:layout_width="200dp"
android:layout_height="200dp"
android:layout_centerHorizontal="true"
android:layout_marginTop="40dp"
android:contentDescription="@string/app_name"
android:src="@drawable/bunny" />
<LinearLayout
android:id="@+id/linear1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@id/imageview"
android:layout_marginTop="30dp"
android:orientation="horizontal"
android:weightSum="3">

<!--To start the blink animation of the image-->


<Button
android:id="@+id/BTNblink"
style="@style/TextAppearance.AppCompat.Widget.Button"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:layout_weight="1"
android:padding="3dp"
android:text="@string/blink"
android:textColor="@color/white" />
• Using a LinearLayout inside a RelativeLayout combines the strengths
of both layouts, allowing for more complex and flexible user interface
designs. It provides the sequential arrangement capabilities of
LinearLayout and the positional flexibility of RelativeLayout, making it
easier to build organized and maintainable layouts.
<!--To start the rotate animation of the image-->
<Button
android:id="@+id/BTNrotate"
style="@style/TextAppearance.AppCompat.Widget.Button"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:layout_weight="1"
android:padding="3dp"
android:text="@string/clockwise"
android:textColor="@color/white" />
<!--To start the fading animation of the image-->
<Button
android:id="@+id/BTNfade"
style="@style/TextAppearance.AppCompat.Widget.Button"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:layout_weight="1"
android:padding="3dp"
android:text="@string/fade"
android:textColor="@color/white" />

</LinearLayout>
<LinearLayout
android:id="@+id/linear2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@id/linear1"
android:layout_marginTop="30dp"
android:orientation="horizontal"
android:weightSum="3">

<!--To start the move animation of the image-->


<Button
android:id="@+id/BTNmove"
style="@style/TextAppearance.AppCompat.Widget.Button"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:layout_weight="1"
android:padding="3dp"
<!--To start the slide animation of the image-->
<Button
android:id="@+id/BTNslide"
style="@style/TextAppearance.AppCompat.Widget.Button"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:layout_weight="1"
android:padding="3dp"
android:text="@string/slide"
android:textColor="@color/white" />
<!--To start the zoom animation of the image-->
<Button
android:id="@+id/BTNzoom"
style="@style/TextAppearance.AppCompat.Widget.Button"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:layout_weight="1"
android:padding="3dp"
android:text="@string/zoom"
android:textColor="@color/white" />

</LinearLayout>
<!--To stop the animation of the image-->
<Button
android:id="@+id/BTNstop"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@id/linear2"
android:layout_marginLeft="30dp"
android:layout_marginTop="30dp"
android:layout_marginRight="30dp"
android:text="@string/stop_animation" />

</RelativeLayout>
• Step 5: Create 6 different types of animation for ImageView
• To create new animations we have to create a new directory for
storing all our animations. Navigate to the app > res > Right-Click on
res >> New >> Directory >> Name your directory as “anim”. Inside
this directory, we will create our animations. For creating a new anim
right click on the anim directory >> Animation Resource file and give
the name to your file. Below is the code snippet for 6 different
animations.
1) Blink Animation

<?xml version="1.0" encoding="utf-8"?>


<set xmlns:android="http://schemas.android.com/apk/res/android">
<alpha android:fromAlpha="0.0"
android:toAlpha="1.0"
android:interpolator="@android:anim/accelerate_interpolator"
android:duration="500"
android:repeatMode="reverse"
android:repeatCount="infinite"/>
</set>
Blink animation
A blink animation is a visual effect where an object, such as text or an image, alternates rapidly
between being visible and invisible. In the context of Android development, a blink animation
typically involves fading an object in and out at regular intervals to create the appearance of blinking.

• Here's how a blink animation works:

• Initial Visibility: The object is initially visible on the screen.


• Fade Out: The object gradually fades out (becomes transparent) over a specified duration. This step
can be achieved using alpha animation, where the alpha value (opacity) of the object decreases
from 1 (fully visible) to 0 (completely transparent).
• Invisibility: Once the object's alpha value reaches 0, it becomes invisible.
• Repeat: After the object becomes invisible, the animation repeats from step 1. The object fades
back in, becoming visible again, and the cycle continues.
• The <set> element is a container for a set of animations that can be played together. The
xmlns:android attribute defines the XML namespace for Android attributes.
• <alpha>: Defines an alpha (transparency) animation.
• android:fromAlpha="0.0": The starting alpha value (0.0 means fully transparent).
• android:toAlpha="1.0": The ending alpha value (1.0 means fully opaque).
• android:interpolator="@android:anim/accelerate_interpolator": Specifies the
interpolator to use, which in this case is an accelerating interpolator. This makes the
animation start slowly and then speed up.
• android:duration="500": The duration of the animation in milliseconds (500ms).
• android:repeatMode="reverse": When the animation reaches the end, it reverses back to
the start.
• android:repeatCount="infinite": The animation repeats indefinitely.
Alpha Animation:
• Alpha animation in Android deals with the transparency of a view. It allows
you to animate the opacity of a view, transitioning it between fully transparent
and fully opaque states.

• alpha: This property defines the transparency level of a view. It ranges from
0.0 (fully transparent) to 1.0 (fully opaque).
• fromAlpha: The starting alpha value of the animation.
• toAlpha: The ending alpha value of the animation.
• In the above code snippet, the alpha tag specifies an animation that
transitions a view's alpha from 0.0 (fully transparent) to 1.0 (fully opaque).
Delta in Animations:
• Delta generally refers to a change in a specific property over time
during an animation. For example, in translation animations, delta
values define how much a view should move from its original
position.

• fromXDelta / toXDelta: Horizontal change in the X coordinate.


2) Fade Animation
• A fade animation in Android is a type of animation that changes the transparency of a view
over time, creating a smooth transition effect where the view gradually appears (fades in) or
disappears (fades out). This type of animation is commonly used to draw attention to a view
or to transition between different views in a subtle and visually appealing way.
• Key Concepts of Fade Animation:
1.Alpha Property:
1. The alpha property controls the opacity of a view, with values ranging from 0.0 (completely transparent)
to 1.0 (completely opaque).
2. By animating this property, you can create fade effects.
2.Fade In and Fade Out:
1. Fade In: The view starts from being completely transparent (alpha = 0) and gradually becomes fully
opaque (alpha = 1).
2. Fade Out: The view starts from being fully opaque (alpha = 1) and gradually becomes completely
transparent (alpha = 0).
2) Fade Animation
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android"
android:interpolator="@android:anim/accelerate_interpolator">

<!-- duration is the time for which animation will work-->


<alpha
android:duration="1000"
android:fromAlpha="0"
android:toAlpha="1" />

<alpha
android:duration="1000"
android:fromAlpha="1"
android:startOffset="2000"
android:toAlpha="0" />

</set>
Interpolator
• An interpolator in Android defines the rate of change of an animation, influencing the
pacing of the animation. It determines how the animation progresses over time, providing
different effects such as acceleration, deceleration, or repeating patterns. Common
interpolators include:

• LinearInterpolator: Changes at a constant rate.


• AccelerateInterpolator: Starts slowly and speeds up.
• DecelerateInterpolator: Starts quickly and slows down.
• AccelerateDecelerateInterpolator: Starts and ends slowly but speeds up in the middle.
• BounceInterpolator: Bounces at the end.
• CycleInterpolator: Repeats the animation for a specified number of cycles.
• OvershootInterpolator: Exceeds the end value and then comes back.
Move animation
• A move animation, also known as a translation animation, involves changing the
position of an object on the screen smoothly over time. In Android development, you
can achieve a move animation using the Animation class or Animator objects.

• Here's how a move animation typically works:


• Initial Position: The object is initially located at a specific position on the screen.
• Transition: The object moves from its initial position to a new position smoothly over
a specified duration.
• Final Position: Once the animation completes, the object remains at its final position.
• Move animations can be used to create various effects in your app, such as sliding
menus, draggable elements, or transitions between different views.
Set Translator
• A translator in Android animations typically refers to a translation
animation, which moves a view from one position to another. The key
attributes and classes for translation animations include:

• android:fromXDelta and android:toXDelta: Define the change in the


X coordinate.
• android:fromYDelta and android:toYDelta: Define the change in the Y
coordinate.
• TranslateAnimation class: Used to create translation animations
programmatically.
3) Move Animation
<?xml version="1.0" encoding="utf-8"?>
<set
xmlns:android="http://schemas.android.com/apk
/res/android"
android:interpolator="@android:anim/
linear_interpolator"
android:fillAfter="true">

<translate
android:fromXDelta="0%p"
android:toXDelta="75%p"
android:duration="700" />
</set>
Rotate animation
• A rotate animation in Android involves changing the orientation of an object smoothly over
time. It creates a visual effect where the object appears to rotate around a specified pivot
point. This animation can be used to add dynamism and visual interest to elements within
your Android application.

Here's how a rotate animation typically works:

• Initial Orientation: The object is initially positioned with a certain orientation on the screen.
• Rotation: The object smoothly rotates around a specified pivot point. The rotation can be
clockwise or counterclockwise and can be defined by specifying the starting and ending
angles.
• Final Orientation: Once the animation completes, the object remains in its final rotated
position.
4) Rotate Animation
<?xml version="1.0" encoding="utf-8"?>
<set
xmlns:android="http://schemas.android.com/apk/res/android">
<rotate
android:duration="6000"
android:fromDegrees="0"
android:pivotX="50%"
android:pivotY="50%"
android:toDegrees="360" />

<rotate
android:duration="6000"
android:fromDegrees="360"
android:pivotX="50%"
android:pivotY="50%"
android:startOffset="5000"
android:toDegrees="0" />

</set>
EXPLAINATION
• <rotate>: This defines a rotate animation. The duration attribute
specifies the duration of the animation in milliseconds.
• The fromDegrees attribute specifies the starting rotation angle in
degrees. The pivotX and pivotY attributes specify the pivot point (the
point around which the rotation occurs), where 50% means the
center of the view.
• The toDegrees attribute specifies the final rotation angle in degrees.
• The first <rotate> element rotates the object from 0 degrees to 360
degrees over a duration of 6000 milliseconds (6 seconds). It rotates
around its center (pivotX="50%" and pivotY="50%").

• The second <rotate> element then reverses the rotation. It starts from 360
degrees (the final angle of the previous animation) and rotates back to 0
degrees over a duration of 6000 milliseconds (6 seconds), but with a start
delay of 5000 milliseconds (5 seconds) due to the startOffset attribute.
This means it will start its rotation 5 seconds after the first rotation
completes.
Slide Animation
• A slide animation in Android involves moving an object smoothly from one position to another,
typically horizontally or vertically. It creates a visual effect where the object appears to slide
across the screen. Slide animations are commonly used for transitions between different views
or to reveal hidden content.

Here's how a slide animation typically works:

• Initial Position: The object is initially located at a specific position on the screen.
• Transition: The object smoothly moves from its initial position to a new position.
• Final Position: Once the animation completes, the object remains at its final position.
• Slide animations can move objects either horizontally (left to right or right to left) or vertically
(upwards or downwards). You can control the duration, acceleration, and deceleration of the
animation to achieve different effects.
5) Slide Animation
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android"
android:fillAfter="true" >
<scale
android:duration="500"
android:fromXScale="1.0"
android:fromYScale="1.0"
android:interpolator="@android:anim/linear_interpolator"
android:toXScale="1.0"
android:toYScale="0.0" />
</set>
6) Zoom Animation
• A zoom animation in Android involves changing the scale of an object smoothly over time,
making it appear to grow larger or smaller. This animation creates a visual effect where the
object appears to zoom in or out. Zoom animations can be used to focus attention on specific
elements, provide feedback, or enhance user interactions.

Here's how a zoom animation typically works:

• Initial Scale: The object is initially displayed at a certain scale (size) on the screen.

• Zooming: The object smoothly changes its scale, either increasing (zooming in) or decreasing
(zooming out) over a specified duration.

• Final Scale: Once the animation completes, the object remains at its final scale.
6) Zoom Animation
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android"
android:fillAfter="true" >

<scale
android:interpolator="@android:anim/linear_interpolator"
android:duration = "1000"
android:fromXScale = "1"
android:fromYScale = "1"
android:pivotX = "50%"
android:pivotY = "50%"
android:toXScale = "2"
android:toYScale = "2"/>
</set>
• A value of 2 means the view will be scaled to twice its original size.
• A value of 1 means no scaling, indicating that the view initially
appears at its original size.

• Android:pivotX="50%" and android:pivotY="50%": These attributes


specify the pivot point (or anchor point) around which the scaling
transformation occurs. In this case, 50% indicates that the pivot point
is located at the center of the view.
• Step 6: Working with the MainActivity.java file
• Add animation to the ImageView by clicking a specific Button.
Navigate to the app > java > your apps package name >>
MainActivity.java.
java
package com.example.animation;

import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.ImageView;

public class MainActivity extends AppCompatActivity {

ImageView imageView;
Button blinkBTN, rotateBTN, fadeBTN, moveBTN, slideBTN, zoomBTN, stopBTN;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imageView = findViewById(R.id.imageview);
blinkBTN = findViewById(R.id.BTNblink);
rotateBTN = findViewById(R.id.BTNrotate);
fadeBTN = findViewById(R.id.BTNfade);
moveBTN = findViewById(R.id.BTNmove);
slideBTN = findViewById(R.id.BTNslide);
zoomBTN = findViewById(R.id.BTNzoom);
stopBTN = findViewById(R.id.BTNstop);
• imageView = findViewById(R.id.imageview);: This line initializes an
ImageView variable named imageView by finding the view with the
specified id (R.id.imageview) from the activity's layout. This is typically
used to get a reference to an ImageView defined in the layout XML
file.
• Below code snippets sets up a click listener for a button (assuming
blinkBTN is a reference to a button in your Android application's
layout XML file). When the button is clicked, it triggers an animation
on an image view (imageView).
blinkBTN.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// To add blink animation
Animation animation = AnimationUtils.loadAnimation(getApplicationContext(), R.anim.blink);
imageView.startAnimation(animation);
}
});
Explaination
• blinkBTN.setOnClickListener(...): This sets up a click listener for the button
named blinkBTN. When the button is clicked, the code inside the onClick
method will execute.

• new View.OnClickListener() { ... }: This part of the code creates an instance of


the View.OnClickListener interface using an anonymous inner class. It's a way
to define a click listener inline without explicitly creating a separate class.

• public void onClick(View v) { ... }: This is the onClick method, which gets
called when the button is clicked. Inside this method, you define what should
happen when the button is clicked.
Explaination
• Animation animation =
AnimationUtils.loadAnimation(getApplicationContext(),
R.anim.blink);: Here, an animation is loaded from an XML resource
file named blink.xml. This file presumably contains the definition for
the animation effect you want to apply.

• imageView.startAnimation(animation);: Finally, the loaded animation


is applied to an imageView using the startAnimation method.
rotateBTN.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// To add rotate animation
Animation animation = AnimationUtils.loadAnimation(getApplicationContext(), R.anim.rotate);
imageView.startAnimation(animation);
}
});
fadeBTN.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// To add fade animation
Animation animation = AnimationUtils.loadAnimation(getApplicationContext(), R.anim.fade);
imageView.startAnimation(animation);
}
});
moveBTN.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// To add move animation
Animation animation = AnimationUtils.loadAnimation(getApplicationContext(), R.anim.move);
imageView.startAnimation(animation);
}
});
slideBTN.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// To add slide animation
Animation animation = AnimationUtils.loadAnimation(getApplicationContext(),
R.anim.slide);
imageView.startAnimation(animation);
}
});
zoomBTN.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// To add zoom animation
Animation animation = AnimationUtils.loadAnimation(getApplicationContext(), R.anim.zoom);
imageView.startAnimation(animation);
}
});
stopBTN.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// To stop the animation going on imageview
imageView.clearAnimation();
}
});
}
}
Quiz 3
• Explain the lifecycle of fragments in android, detailing each stage and
its corresponding methods.
• Describe the Key Properties of Material Design EditText in Android

You might also like