Property Animation API was introduced by Google in Android 3.0 which gives us the flexibility to change object properties over a certain time interval. The Animations Framework allows us to create visually attractive animations and transitions in our apps. Using the animations, one can turn their good looking app into an excellent and highly usable app.
Animations are useful when the screen changes state, i.e when the content loads or new actions become available.
Animation is the process of creating motion and shape change. In this Tutorial we will show how simple animations encourage you to use them more freely and confidently.
Animations notify users about what’s going on in your app and improve the mental model of your app’s interface.
Table Of Contents
View Animation:
This is the simplest animation used in Android. It define the properties of our Views that should be animated using a technique called Tween Animation.It take the following parameters i.e. size, time duration , rotation angle, start value , end value, and perform the required animation on that object.You can execute the animation by specifying transformations on your View. This can be done in XML resource files or programmatically.
Android View animation can make animation on any View objects, such as ImageView, TextView or Button objects. View animation can only animate simple properties like position, size, rotation, and the alpha property that allows you animate the transparency of a View.
The drawback of this mechanism is that it can only be applied to Views.
Property Animation:
This animation was introduced in Android 3.0 (API level 11). It allows the user to animate anything.
Property animations are highly customizable, you can specify the duration, the number of repeats, the type of interpolation, and the frame rate of the animation. The Property Animation system is always preferred for more complex animations.
Property animations allow us to animate any property of any object from one value to another over a specified duration. Let us take an example, imagine you wanted to animate the 3d rotation using the rotationX or rotationY properties that were introduced in API 11. Or maybe you want to animate a color change or animate the change of a drawable. This is not possible by using View Animations. For this purpose Property Animation is used .
You are not limited by predefined animation types or by the type of object that you want to animate. At first the usage of the Property Animation System might seem a little complicated. However, in most cases you can use the very versatile ObjectAnimator that uses reflection. The ObjectAnimator makes creating Property Animations almost as easy as creating View Animations.
Common properties commonly animated on views include:
Property | Description |
---|---|
alpha | Fade in or out |
rotation, rotationX, rotationY | Spin or flip |
scaleX ,scaleY | Grow or shrink |
x,y,z | Position |
translationX, translationY, translationZ (API 21+) | Offset from Position |
Drawable Animation:
This animation allows the user to load drawable resources and display them one frame after another. This method of animation is useful when user wants to animate things that are easier to represent with Drawable resources.
To use Animations in Android , Android has provided us a class called Animation.
To perform animation in android , we will call a static function loadAnimation()(this method is used to load animation) of the class AnimationUtils. We are going to receive the result in an instance of Animation Object. Its syntax is as follows −
Animation animation =AnimationUtils.loadAnimation(getApplicationContext(), R.anim.myanimation);
Second parameter refers to our animation.xml file.It is created under res directory(res->anim->myanimation.xml)
The Animation class has many methods given below:
1.start(): This method will start the animation.
2.setDuration(long duration): This method sets the duration of an animation.
3.getDuration(): This method gets the duration.
4.end(): This method ends the animation.
5.cancel(): This method cancels the animation.
Animation listeners can be set by implementing AnimationListener in our Activity. If you will use AnimationListener, then you will have to override following methods.
onAnimationStart –
@Override public void onAnimationStart(Animation animation) { }
onAnimationEnd –
@Override public void onAnimationEnd(Animation animation) { }
onAnimationRepeat –
@Override public void onAnimationRepeat(Animation animation) { }
Scale Animation
Scale Animation is used to make a smaller or larger view either on x axis or y axis. Pivot point can also be specified around which we want the animation to take place.
Rotate Animation
Rotate Animation is used to rotate a view around a pivot point by a certain number of degrees.
Translate Animation
Translate Animation is used to move a view along the x or y axis.
Alpha Animation
Transparency of a view can be changed by Alpha Animation
The dictionary meaning of Interpolate is to alter, intercept or insert in between two things or events.
It is used to insert or apply an additional animation effects between the start and the end value of the property of an object.It is also used to define the rate of change of an animation.
Types of Interpolator:
1.Linear Interpolator: It is the default interpolator of all animations. It defines that the rate of the change of the animation is constant.
2.Accelerate Interpolator: Accelerates the moving of the view, it starts out slowly and then accelerates until it reaches the final position.
3.Decelerate Interpolator: Does the opposite of the accelerate interpolator. It starts out fast and the slows down.
4.Accelerate Decelerate Interpolator: Makes the moving go slow at the beginning and the end, but fast in the middle.
5.Anticipate Interpolator: Moves the animation backwards before it starts
6.Overshoot Interpolator: Does the opposite of the anticipate interpolator. It make the animation to go further than the defined destintion, and then get back to the defined destination.
7.Anticipate Overshoot Interpolator: Combines the anticipate and the overshoot interpoplator. The change starts backward then flings forward and overshoots the target value and finally goes back to the final value.
8.Bounce Interpolator: Makes an bounce animation before the desired animation ends.
9.Cycle Interpolator: Repeats the animation for a specified number of cycles.
1. android:duration: The duration in which animation is completed is referred to as duration attribute. It refers to the ideal duration to show the transition on the screen.
android:duration="1500"
2. android:fillAfter: This attribute defines whether the view should be visible or not at the end of the animation.We have set its value true in our animation. If it would set to false then element changes comes to its previous state after the animation.
android:fillAfter="true"
3. android:interpolator: This property refers to the rate of change in animation. You can define your own interpolators using the time as the constraint. In this animation we have used an inbuilt interpolator i.e. linear interpolator.
android:interpolator="@android:anim/linear_interpolator"
4. android:startOffset: It refers to the waiting time before an animation starts.
android:startOffset="2000"
5. android:repeatMode: When user wants the animation to be repeated then this attribute is used
android:repeatMode="restart"
6. android:repeatCount: This attribute defines the number of repetitions on animation.
android:repeatCount="infinite"
Below we will create one complete animation example in Android Studio which will display 14 different types of Animation. We will put the 14 types of Animation names in NavigationDrawer menu and onclick of names in menu that particular Animation will work.
Below you can download code, see final output and step by step explanation of example.
Step 1: Create a blank new project and name it AnimationExample
Step 2: Select Navigation Drawer Activity from Create New Project dialog, click next and then finish.
Important Note: When you select Navigation Drawer Activity for your project it will create four xml files in res =>layout folder and the content_main.xml file among four is important which we will use in our project.
Step 3: Setting up NavigationDrawer for our example to show different types of Animations list in Navigation menu.
activity_main.xml code:
<?xml version="1.0" encoding="utf-8"?> <android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/drawer_layout" android:layout_width="match_parent" android:layout_height="match_parent" android:fitsSystemWindows="true" tools:openDrawer="start"> <include layout="@layout/app_bar_main" android:layout_width="match_parent" android:layout_height="match_parent" /> <android.support.design.widget.NavigationView android:id="@+id/nav_view" android:layout_width="wrap_content" android:layout_height="match_parent" android:layout_gravity="start" android:fitsSystemWindows="true" app:headerLayout="@layout/nav_header_main" app:menu="@menu/activity_main_drawer" /> </android.support.v4.widget.DrawerLayout>
app_bar_main.xml code
<?xml version="1.0" encoding="utf-8"?> <android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context="com.example.abhishek.animationexample.MainActivity"> <android.support.design.widget.AppBarLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:theme="@style/AppTheme.AppBarOverlay"> <android.support.v7.widget.Toolbar android:id="@+id/toolbar" android:layout_width="match_parent" android:layout_height="?attr/actionBarSize" android:background="?attr/colorAccent" app:popupTheme="@style/AppTheme.PopupOverlay" /> </android.support.design.widget.AppBarLayout> <include layout="@layout/content_main" /> </android.support.design.widget.CoordinatorLayout>
content_main.xml code
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" app:layout_behavior="@string/appbar_scrolling_view_behavior" tools:context=".MainActivity" tools:showIn="@layout/app_bar_main"> <FrameLayout android:id="@+id/content_frame" android:layout_width="match_parent" android:layout_height="match_parent" /> </RelativeLayout>
nav_header_main.xml or nav_header.xml code:
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" android:layout_width="match_parent" android:layout_height="@dimen/nav_header_height" android:background="@drawable/side_nav_bar" android:gravity="bottom" android:orientation="vertical" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" android:theme="@style/ThemeOverlay.AppCompat.Dark" android:weightSum="1"> <ImageView android:id="@+id/imageView" android:layout_width="wrap_content" android:layout_height="wrap_content" android:src="@drawable/animation" android:layout_alignParentTop="true" android:layout_alignRight="@+id/textView" android:layout_alignEnd="@+id/textView" android:layout_marginRight="172dp" android:layout_marginEnd="172dp" /> <TextView android:id="@+id/textView" android:layout_width="140dp" android:layout_height="55dp" android:text="ANIMATION EXAMPLE" android:textColor="#0606ea" android:textSize="11dp" android:textStyle="bold" android:layout_alignParentBottom="true" android:layout_alignParentRight="true" android:layout_alignParentEnd="true" android:layout_marginBottom="17dp" /> </RelativeLayout>
Step 4: Open activity_main_drawer.xml file available in res=>menu folder:
Put the below code in it. In this Layout we will define different items we will create in NavigationDrawer.
<?xml version="1.0" encoding="utf-8"?> <menu xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:android="http://schemas.android.com/apk/res/android"> <group android:checkableBehavior="single"> <item android:id="@+id/nav_zoomin" android:title="Zoom In" /> <item android:id="@+id/nav_zoomout" android:title="Zoom Out" /> <item android:id="@+id/nav_rotate" android:title="Rotate" /> <item android:id="@+id/nav_move" android:title="Move" /> <item android:id="@+id/nav_bounce" android:title="Bounce" /> <item android:id="@+id/nav_Blink" android:title="Blink" /> <item android:id="@+id/nav_slideup" android:title="Slide Up" /> <item android:id="@+id/nav_slidedown" android:title="Slide Down" /> <item android:id="@+id/nav_fade" android:title="Fade Animation" /> <item android:id="@+id/nav_sequentialanimation" android:title="Sequential Animation" /> <item android:id="@+id/nav_togetheranimation" android:title="Together Animation" /> <item android:id="@+id/nav_flip" android:title="Flip Animation" /> <item android:id="@+id/nav_drawable" android:title="Drawable Animation" /> <item android:id="@+id/nav_swap" android:title="Swap Animation"/> </group> </menu>
Step 5: Now open MainActivity.java file and put the below code.
To make Drawer Menus functional we have used OnNavigationItemSelected() method. Then displaySelectedScreen() is used where a fragment object is created and intializing the fragment object which is selected.
package com.example.abhishek.animationexample; import android.support.v4.app.Fragment; import android.os.Bundle; import android.support.v4.app.FragmentTransaction; import android.support.design.widget.NavigationView; import android.support.v4.view.GravityCompat; import android.support.v4.widget.DrawerLayout; import android.support.v7.app.ActionBarDrawerToggle; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.view.Menu; import android.view.MenuItem; import com.example.abhishek.animationexample.fragment.blinkfragment; import com.example.abhishek.animationexample.fragment.bouncefragment; import com.example.abhishek.animationexample.fragment.drawableanimationfragment; import com.example.abhishek.animationexample.fragment.fadefragment; import com.example.abhishek.animationexample.fragment.flipfragment; import com.example.abhishek.animationexample.fragment.movefragment; import com.example.abhishek.animationexample.fragment.rotatefragment; import com.example.abhishek.animationexample.fragment.sequentialanimationfragment; import com.example.abhishek.animationexample.fragment.slidedownfragment; import com.example.abhishek.animationexample.fragment.slideupfragment; import com.example.abhishek.animationexample.fragment.swapanimationfragment; import com.example.abhishek.animationexample.fragment.togetheranimationfragment; import com.example.abhishek.animationexample.fragment.zoominfragment; import com.example.abhishek.animationexample.fragment.zoomoutfragment; public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout); ActionBarDrawerToggle toggle = new ActionBarDrawerToggle( this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close); drawer.setDrawerListener(toggle); toggle.syncState(); NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view); navigationView.setNavigationItemSelectedListener(this); } @Override public void onBackPressed() { DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout); if (drawer.isDrawerOpen(GravityCompat.START)) { drawer.closeDrawer(GravityCompat.START); } else { super.onBackPressed(); } } private void displaySelectedScreen(int itemId) { Fragment fragment = null; switch (itemId) { case R.id.nav_bounce: fragment = new bouncefragment(); break; case R.id.nav_Blink: fragment = new blinkfragment(); break; case R.id.nav_zoomin: fragment = new zoominfragment(); break; case R.id.nav_zoomout: fragment = new zoomoutfragment(); break; case R.id.nav_rotate: fragment = new rotatefragment(); break; case R.id.nav_move: fragment = new movefragment(); break; case R.id.nav_slideup: fragment = new slideupfragment(); break; case R.id.nav_slidedown: fragment = new slidedownfragment(); break; case R.id.nav_sequentialanimation: fragment = new sequentialanimationfragment(); break; case R.id.nav_togetheranimation: fragment = new togetheranimationfragment(); break; case R.id.nav_flip: fragment = new flipfragment(); break; case R.id.nav_fade: fragment= new fadefragment(); break; case R.id.nav_drawable: fragment = new drawableanimationfragment(); break; case R.id.nav_swap: fragment = new swapanimationfragment(); break; } if (fragment != null) { FragmentTransaction ft = getSupportFragmentManager().beginTransaction(); ft.replace(R.id.content_frame, fragment); ft.commit(); } DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout); drawer.closeDrawer(GravityCompat.START); } @Override public boolean onNavigationItemSelected(MenuItem item) { displaySelectedScreen(item.getItemId()); return true; } }
Step 6: Creating Screens for Navigation Menus using Fragment
Whenever we click on a navigation item from the drawer, a respective screen should open. We will use fragments for this purpose. Below is the code for each fragment xml and associated java file. We will create a directory with name fragment inside it and we will create our fragment.java files.
Step 6.1. Setting Up Blink Animation:
Fade in and Fade out animation performed infinitely in reverse mode each time is referred to as Blink Animation.
android:repeatMode=”reverse” – useful when you want the animation to be repeat
android:repeatCount=”infinite” – Defines the number of repetitions on animation. We have set this value to infinite now animation will repeat infinite times
fragment_blink.xml in Layout:
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> <ImageView android:id="@+id/imageblink" android:src="@drawable/blink" android:layout_width="wrap_content" android:layout_height="wrap_content" android:visibility="gone" android:layout_marginBottom="38dp" android:layout_above="@+id/btnStart" android:layout_alignParentLeft="true" android:layout_alignParentStart="true" android:layout_marginLeft="10dp" android:layout_marginStart="10dp" /> <Button android:id="@+id/btnStart" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Start Blinking" android:layout_marginBottom="17dp" android:layout_alignParentBottom="true" android:layout_alignParentRight="true" android:layout_alignParentEnd="true" android:layout_marginRight="34dp" android:layout_marginEnd="34dp" /> </RelativeLayout>
blinkfragment.java in fragment folder:
package com.example.abhishek.animationexample.fragment; import android.app.Activity; import android.support.v4.app.Fragment; import android.os.Bundle; import android.support.annotation.Nullable; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.animation.Animation; import android.view.animation.AnimationUtils; import android.widget.Button; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import com.example.abhishek.animationexample.R; import static com.example.abhishek.animationexample.R.drawable.animation; /** * Created by abhiandroid */ public class blinkfragment extends Fragment implements Animation.AnimationListener { ImageView imageView; Button btnStart; View view; Animation animBlink; @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) { view = inflater.inflate(R.layout.fragment_blink, container, false); imageView = (ImageView) view.findViewById(R.id.imageblink); btnStart = (Button)view.findViewById(R.id.btnStart); animBlink = AnimationUtils.loadAnimation(getContext(), R.anim.blink); animBlink.setAnimationListener(this); btnStart.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { imageView.setVisibility(View.VISIBLE); imageView.startAnimation(animBlink); } }); return view; } @Override public void onAnimationStart(Animation animation) { } @Override public void onAnimationEnd(Animation animation) { } @Override public void onAnimationRepeat(Animation animation) { } }
Step 6.1.1 : Now we will create anim folder and blink.xml animation resource file in Android Studio.
blink.xml (Animation Resource file create in anim folder)
<?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="600" android:repeatMode="repeat" android:repeatCount="infinite"/> </set>
Step 6.2. Setting up Bounce Animation:
The animation which ends in bouncing fashion is known as bouncing animation For this set android:interpolator value to @android:anim/bounce_interpolator.
fragment_bounce.xml (Create in Layout folder):
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" > <ImageView android:id="@+id/imgbounce" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerInParent="true" android:src="@drawable/bounce" android:visibility="gone" /> <Button android:id="@+id/btn_bounce" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginBottom="26dp" android:text="Start Bouncing" android:layout_alignParentBottom="true" android:layout_alignParentRight="true" android:layout_alignParentEnd="true" android:layout_marginRight="13dp" android:layout_marginEnd="13dp" /> </RelativeLayout>
bouncefragment.java (Create in Fragment folder)
package com.example.abhishek.animationexample.fragment; import android.support.v4.app.Fragment; import android.os.Bundle; import android.support.annotation.Nullable; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.animation.Animation; import android.view.animation.AnimationUtils; import android.widget.Button; import android.widget.ImageView; import com.example.abhishek.animationexample.R; /** * Created by abhiandroid */ public class bouncefragment extends Fragment implements Animation.AnimationListener { ImageView imageView; Button btnStart; View view; Animation animBounce; @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) { view = inflater.inflate(R.layout.fragment_bounce, container, false); imageView = (ImageView) view.findViewById(R.id.imgbounce); btnStart = (Button)view.findViewById(R.id.btn_bounce); animBounce = AnimationUtils.loadAnimation(getContext(), R.anim.bounce ); animBounce.setAnimationListener(this); btnStart.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { imageView.setVisibility(View.VISIBLE); imageView.startAnimation(animBounce); } }); return view; } @Override public void onAnimationStart(Animation animation) { } @Override public void onAnimationEnd(Animation animation) { } @Override public void onAnimationRepeat(Animation animation) { } }
bounce.xml (Animation Resource File in anim folder)
<?xml version="1.0" encoding="utf-8"?> <set xmlns:android="http://schemas.android.com/apk/res/android" android:fillAfter="true" android:interpolator="@android:anim/bounce_interpolator"> <scale android:duration="800" android:fromXScale="2.0" android:fromYScale="0.0" android:toXScale="1.0" android:toYScale="1.0" /> </set>
Step 6.3 – Setting Up Drawable Animation:
Drawable animation loads Drawable resources one after another to create an animation.The AnimationDrawable class is the basis for Drawable animations.
In the drawable folder add images images1.png, images2.png , images3.png, images4.png.
fragment_drawable.xml (Create in Layout Folder):
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent"> <TextView android:id="@+id/textView2" android:textColor="#c008ce" android:textStyle="italic" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/touch_start_animation" android:layout_above="@+id/ball" android:layout_centerHorizontal="true" android:layout_marginBottom="45dp" /> <ImageView android:id="@+id/ball" android:layout_width="241dp" android:layout_height="182dp" android:src="@drawable/ball" android:layout_marginBottom="151dp" android:layout_alignParentBottom="true" android:layout_centerHorizontal="true" /> </RelativeLayout>
drawableanimationfragment.java (Create in Fragment folder):
package com.example.abhishek.animationexample.fragment; import android.graphics.drawable.AnimationDrawable; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.support.v7.app.ActionBarActivity; import android.view.LayoutInflater; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import com.example.abhishek.animationexample.R; /** * Created by abhishek on 31/10/17. */ public class drawableanimationfragment extends Fragment { View view; @Nullable @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { view = inflater.inflate(R.layout.fragment_drawable, container, false); final ImageView ball = (ImageView) view.findViewById(R.id.ball); ball.setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { if (event.getAction() == MotionEvent.ACTION_DOWN) { AnimationDrawable animation = (AnimationDrawable) ball.getDrawable(); animation.stop(); animation.selectDrawable(0); animation.start(); return true; } return false; } }); return view; } }
Create ball.xml under drawable(res->drawable->ball.xml)
The XML file consists of an <animation-list> element . This animation runs for four frames. We have set android:oneshot attribute of the list true, this will cycle just once ,then stop and hold on the last frame.
<?xml version="1.0" encoding="utf-8"?> <animation-list xmlns:android="http://schemas.android.com/apk/res/android" android:oneshot="true"> <item android:drawable="@drawable/images4" android:duration="400" /> <item android:drawable="@drawable/images3" android:duration="400" /> <item android:drawable="@drawable/images2" android:duration="400" /> <item android:drawable="@drawable/images1" android:duration="400" /> </animation-list>
Step 6.4 – Setting Up Fade Animation:
<alpha> tag which defines alpha value is used for fade animation
alpha refers to the opacity of an object. An object with lower alpha values is more transparent, while an object with higher alpha values is less transparent, more opaque.
Fade in animation is nothing but increasing alpha value from 0 to 1.
Fade out animation refers to decrease the alpha value from 1 to 0.
Fade out animation is just opposite of fade in animation.
fragment_fade.xml (Create in Layout Folder):
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:gravity="center"> <ImageView android:id="@+id/imgfade" android:layout_width="222dp" android:layout_height="200dp" android:src="@drawable/fade" android:layout_marginTop="92dp" android:layout_alignParentTop="true" android:layout_alignParentRight="true" android:layout_alignParentEnd="true" android:layout_marginRight="65dp" android:layout_marginEnd="65dp" /> <Button android:id="@+id/btnfade" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Start" android:layout_marginBottom="40dp" android:layout_marginRight="42dp" android:layout_marginEnd="42dp" android:layout_alignParentBottom="true" android:layout_alignParentRight="true" android:layout_alignParentEnd="true" /> </RelativeLayout>
fadefragment.java in fragment folder
package com.example.abhishek.animationexample.fragment; import android.support.v4.app.Fragment; import android.os.Bundle; import android.support.annotation.Nullable; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.animation.Animation; import android.view.animation.AnimationUtils; import android.widget.Button; import android.widget.ImageView; import com.example.abhishek.animationexample.R; /** * Created by abhiandroid */ public class fadefragment extends Fragment implements Animation.AnimationListener{ @Nullable ImageView imageView; Button btnstart; View view; Animation animFade; @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) { view = inflater.inflate(R.layout.fragment_fade, container, false); imageView = (ImageView) view.findViewById(R.id.imgfade); btnstart = (Button)view.findViewById(R.id.btnfade); animFade = AnimationUtils.loadAnimation(getContext(), R.anim.fade ); animFade.setAnimationListener(this); btnstart.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { imageView.startAnimation(animFade); } }); return view; } @Override public void onAnimationStart(Animation animation) { } @Override public void onAnimationEnd(Animation animation) { } @Override public void onAnimationRepeat(Animation animation) { } }
fade.xml (Animation Resource File in anim folder)
<?xml version="1.0" encoding="utf-8"?> <set xmlns:android="http://schemas.android.com/apk/res/android" android:interpolator="@android:anim/accelerate_interpolator" > <alpha android:fromAlpha="0" android:toAlpha="1" android:duration="2000" > </alpha> <alpha android:startOffset="2000" android:fromAlpha="1" android:toAlpha="0" android:duration="2000" > </alpha> </set>
Step 6.5 – Setting Up Flip Animation:
Flipping Animation makes a nice effect on your game or app. We’ll use two different images—one for the front and one for the back, to create the card flip effect. We will need two animation resources which we will define in XML using objectAnimator.
ObjectAnimator is the subclass of ValueAniamtor that provides support for animating properties on target objects.
attributes:
android:propertyName: Gets the name of the property that will be animated. For example: you can specify “alpha” or a View object.
android:valueTo: The value where the animated property ends.
android:valueFrom: The value where the animated property starts
android:duration: The duration in which animation is completed is referred to as duration attribute. It refers to the ideal duration to show the transition on the screen.
android:repeatMode: “reverse” (useful when you want the animation to be repeated)
android:repeatCount: “infinite” (defines the number of repetitions on animation.We have set this value to infinite now animation will repeat infinite times)
android:startOffset: defines the waiting time before an animation starts.
<objectAnimator xmlns:android="http://schemas.android.com/apk/res/android" android:duration="1000" android:valueTo="200" android:valueType="floatType" android:propertyName="y" android:repeatCount="1" android:repeatMode="reverse"/>
fragment_flip.xml (Create in layout folder):
<?xml version="1.0" encoding="utf-8"?> <FrameLayout 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" > <FrameLayout android:id="@+id/card_back" android:layout_width="match_parent" android:layout_height="match_parent"> <include layout="@layout/card_back" /> </FrameLayout> <FrameLayout android:id="@+id/card_front" android:layout_width="match_parent" android:layout_height="match_parent" android:gravity="center"> <include layout="@layout/card_front" /> </FrameLayout> </FrameLayout>
card_back.xml(create in res->layout->card_back.xml)
<?xml version="1.0" encoding="utf-8"?> <FrameLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> <ImageView android:layout_width="match_parent" android:layout_height="match_parent" android:tint="@color/cardBack" android:padding="16dp" android:src="@drawable/oval"/> <TextView android:layout_width="match_parent" android:layout_height="match_parent" android:text="@string/back" android:textColor="#0606ea" style="@style/Base.TextAppearance.AppCompat.Display1" android:gravity="center"/> </FrameLayout>
card_front.xml(create in res->layout->card_front.xml):
<?xml version="1.0" encoding="utf-8"?> <FrameLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> <ImageView android:layout_width="match_parent" android:layout_height="match_parent" android:tint="@color/cardFront" android:padding="16dp" android:src="@drawable/oval"/> <TextView android:layout_width="match_parent" android:layout_height="match_parent" android:text="@string/front" android:textColor="#b815d9" style="@style/Base.TextAppearance.AppCompat.Display1" android:gravity="center"/> </FrameLayout>
flipfragment.java (Create in fragment folder)
package com.example.abhishek.animationexample.fragment; import android.animation.AnimatorInflater; import android.animation.AnimatorSet; import android.support.v4.app.Fragment; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.support.v7.app.AppCompatActivity; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.animation.Animation; import android.view.animation.AnimationUtils; import android.widget.Button; import android.widget.ImageView; import com.example.abhishek.animationexample.R; /** * Created by abhiandroid */ public class flipfragment extends Fragment { private AnimatorSet mSetRightOut; private AnimatorSet mSetLeftIn; private boolean mIsBackVisible = false; private View mCardFrontLayout; private View mCardBackLayout; ImageView imageView; View view; @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) { view = inflater.inflate(R.layout.fragment_flip, container, false); findViews(); loadAnimations(); flipCard(view); changeCameraDistance(); return view; } private void changeCameraDistance() { int distance = 8000; float scale = getResources().getDisplayMetrics().density * distance; mCardFrontLayout.setCameraDistance(scale); mCardBackLayout.setCameraDistance(scale); } private void loadAnimations() { mSetRightOut = (AnimatorSet) AnimatorInflater.loadAnimator(getContext(), R.anim.out_animation); mSetLeftIn = (AnimatorSet) AnimatorInflater.loadAnimator(getContext(), R.anim.in_animation); } private void findViews() { mCardBackLayout = view.findViewById(R.id.card_back); mCardFrontLayout = view.findViewById(R.id.card_front); } public void flipCard(View view) { if (!mIsBackVisible) { mSetRightOut.setTarget(mCardFrontLayout); mSetLeftIn.setTarget(mCardBackLayout); mSetRightOut.start(); mSetLeftIn.start(); mIsBackVisible = true; } else { mSetRightOut.setTarget(mCardBackLayout); mSetLeftIn.setTarget(mCardFrontLayout); mSetRightOut.start(); mSetLeftIn.start(); mIsBackVisible = false; } } }
in_animation.xml(create in res->anim->in_animation.xml)
<?xml version="1.0" encoding="utf-8"?> <set xmlns:android="http://schemas.android.com/apk/res/android"> <objectAnimator android:valueFrom="1.0" android:valueTo="0.0" android:propertyName="alpha" android:duration="0" /> <objectAnimator android:valueFrom="-180" android:valueTo="0" android:propertyName="rotationY" android:repeatMode="reverse" android:duration="@integer/anim_length" /> <objectAnimator android:valueFrom="0.0" android:valueTo="1.0" android:propertyName="alpha" android:startOffset="@integer/anim_length_half" android:duration="0" /> </set>
out_animation.xml(create in res->anim->out_animation.xml)
<?xml version="1.0" encoding="utf-8"?> <set xmlns:android="http://schemas.android.com/apk/res/android"> <objectAnimator android:valueFrom="0" android:valueTo="180" android:propertyName="rotationY" android:duration="@integer/anim_length" /> <objectAnimator android:valueFrom="1.0" android:valueTo="0.0" android:propertyName="alpha" android:startOffset="@integer/anim_length_half" android:duration="0" /> </set>
oval.xml(create in res->drawable->oval.xml)
<?xml version="1.0" encoding="utf-8"?> <shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="oval"> <corners android:radius="16dp"/> <solid android:color="#fff"/> <stroke android:width="2dp" android:color="#000"></stroke> </shape>
Step 6.6 – Setting Up Move Animation:
<translate> tag is used in this animation in order to control the position of an object . It has the following parameters:
fromXDelta: refres to change in X coordinate to apply at the start of the animation
fromYDelta: refers to change in Y coordinate to apply at the start of the animation
toXDelta: refers to change in X coordinate to apply at the end of the animation
toYDelta: refers to change in Y coordinate to apply at the end of the animation
fragment_move.xml (Create in layout folder):
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:gravity="center"> <ImageView android:id="@+id/imgmove" android:layout_width="150dp" android:layout_height="100dp" android:src="@drawable/move" android:layout_alignParentTop="true" /> <Button android:id="@+id/btnmove" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Start Moving" android:layout_marginRight="21dp" android:layout_marginEnd="21dp" android:layout_marginBottom="39dp" android:layout_alignParentBottom="true" android:layout_alignParentRight="true" android:layout_alignParentEnd="true" /> </RelativeLayout>
movefragment.java(Create in fragment folder):
package com.example.abhishek.animationexample.fragment; import android.support.v4.app.Fragment; import android.os.Bundle; import android.support.annotation.Nullable; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.animation.Animation; import android.view.animation.AnimationUtils; import android.widget.Button; import android.widget.ImageView; import com.example.abhishek.animationexample.R; /** * Created by abhiandroid */ public class movefragment extends Fragment implements Animation.AnimationListener{ @Nullable ImageView imageView; Button btnmove; View view; Animation animMove; @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) { view = inflater.inflate(R.layout.fragment_move, container, false); imageView = (ImageView) view.findViewById(R.id.imgmove); btnmove = (Button)view.findViewById(R.id.btnmove); animMove = AnimationUtils.loadAnimation(getContext(), R.anim.move ); animMove.setAnimationListener(this); btnmove.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { imageView.startAnimation(animMove); } }); return view; } @Override public void onAnimationStart(Animation animation) { } @Override public void onAnimationEnd(Animation animation) { } @Override public void onAnimationRepeat(Animation animation) { } }
move.xml (Create Animation Resource Directory in anim folder):
<?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="60%p" android:duration="1500" /> </set>
Step 6.7 – Setting up rotate animation
<rotate> tag is used to control the rotation of an object in the rotate animation. The rotation takes place in the X-Y plane. (0,0) is the default rotation point.
Attributes that defines rotation angles:
android:fromDegrees: It defines the rotation offset to apply at the start of the animation.
android:toDegrees: It defines the rotation offset to apply at the end of the animation.
Clock wise – use positive toDegrees value
Anti clock wise – use negative toDegrees value
Parameters:
pivotX: refers to X coordinate of the point about which the object is being rotated
pivotY: refers to Y coordinate of the point about which the object is being rotated
android:repeatMode: “reverse”(useful when you want the animation to be repeat)
android:repeatCount: “infinite”(defines the number of repetitions on animation.We have set this value to infinite now animation will repeat infinite times)
android:interpolator: this property refers to the rate of change in animation. You can define your own interpolators using the time as the constraint. In this animation we have used an inbuilt interpolator i.e.cycle interpolator
fragment_rotate.xml (Create in layout folder):
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:gravity="center"> <ImageView android:id="@+id/imgrotate" android:layout_width="222dp" android:layout_height="200dp" android:src="@drawable/rotate" android:layout_marginTop="92dp" android:layout_alignParentTop="true" android:layout_alignParentRight="true" android:layout_alignParentEnd="true" android:layout_marginRight="65dp" android:layout_marginEnd="65dp" /> <Button android:id="@+id/btnrotate" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Start Rotating" android:layout_marginBottom="40dp" android:layout_marginRight="42dp" android:layout_marginEnd="42dp" android:layout_alignParentBottom="true" android:layout_alignParentRight="true" android:layout_alignParentEnd="true" /> </RelativeLayout>
rotatefragment.java: (Create in fragment folder)
package com.example.abhishek.animationexample.fragment; import android.support.v4.app.Fragment; import android.os.Bundle; import android.support.annotation.Nullable; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.animation.Animation; import android.view.animation.AnimationUtils; import android.widget.Button; import android.widget.ImageView; import com.example.abhishek.animationexample.R; /** * Created by abhiandroid */ public class rotatefragment extends Fragment implements Animation.AnimationListener{ @Nullable ImageView imageView; Button btnrotate; View view; Animation animRotate; @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) { view = inflater.inflate(R.layout.fragment_rotate, container, false); imageView = (ImageView) view.findViewById(R.id.imgrotate); btnrotate = (Button)view.findViewById(R.id.btnrotate); animRotate = AnimationUtils.loadAnimation(getContext(), R.anim.rotate ); animRotate.setAnimationListener(this); btnrotate.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { imageView.startAnimation(animRotate); } }); return view; } @Override public void onAnimationStart(Animation animation) { } @Override public void onAnimationEnd(Animation animation) { } @Override public void onAnimationRepeat(Animation animation) { } }
rotate.xml(Create in anim folder):
<?xml version="1.0" encoding="utf-8"?> <set xmlns:android="http://schemas.android.com/apk/res/android"> <rotate android:fromDegrees="0" android:toDegrees="360" android:pivotX="70%" android:pivotY="70%" android:duration="1000" android:repeatMode="restart" android:repeatCount="infinite" android:interpolator="@android:anim/cycle_interpolator"/> </set>
Step 6.8 – Setting Up Sequential Animation:
In this animation we have used startOffset to give delay between animations.
android:startOffset: It refers to the waiting time before an animation starts. This property is mainly used to perform multiple animations in a sequential manner
fragment_sequentialanimation.xml (Create in layout folder):
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent"> <ImageView android:id="@+id/imgsequence" android:layout_width="wrap_content" android:layout_height="wrap_content" android:src="@drawable/sequential" android:layout_marginBottom="309dp" android:layout_above="@+id/btnSequence" android:layout_toStartOf="@+id/btnSequence" /> <Button android:id="@+id/btnSequence" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Start Animation" android:layout_marginBottom="18dp" android:layout_alignParentBottom="true" android:layout_centerHorizontal="true" /> </RelativeLayout>
sequentialanimationfragment.java (Create in fragment folder):
package com.example.abhishek.animationexample.fragment; import android.support.v4.app.Fragment; import android.os.Bundle; import android.support.annotation.Nullable; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.animation.Animation; import android.view.animation.AnimationUtils; import android.widget.Button; import android.widget.ImageView; import com.example.abhishek.animationexample.R; /** * Created by abhishek on 27/10/17. */ public class sequentialanimationfragment extends Fragment implements Animation.AnimationListener{ @Nullable ImageView imageView; Button btnStart; View view; Animation animSequence; @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) { view = inflater.inflate(R.layout.fragment_sequentialanimation, container, false); imageView = (ImageView) view.findViewById(R.id.imgsequence); btnStart = (Button)view.findViewById(R.id.btnSequence); animSequence = AnimationUtils.loadAnimation(getContext(), R.anim.sequential ); animSequence.setAnimationListener(this); btnStart.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { imageView.startAnimation(animSequence); } }); return view; } @Override public void onAnimationStart(Animation animation) { } @Override public void onAnimationEnd(Animation animation) { } @Override public void onAnimationRepeat(Animation animation) { } }
sequential.xml (Create in anim folder):
<?xml version="1.0" encoding="utf-8"?> <set xmlns:android="http://schemas.android.com/apk/res/android" android:fillAfter="true" android:interpolator="@android:anim/linear_interpolator" > <!-- Use startOffset to give delay between animations --> <!-- Move --> <translate android:duration="800" android:fillAfter="true" android:fromXDelta="0%p" android:startOffset="300" android:toXDelta="75%p" /> <translate android:duration="800" android:fillAfter="true" android:fromYDelta="0%p" android:startOffset="1100" android:toYDelta="70%p" /> <translate android:duration="800" android:fillAfter="true" android:fromXDelta="0%p" android:startOffset="1900" android:toXDelta="-75%p" /> <translate android:duration="800" android:fillAfter="true" android:fromYDelta="0%p" android:startOffset="2700" android:toYDelta="-70%p" /> <!-- Rotate 360 degrees --> <rotate android:duration="1000" android:fromDegrees="0" android:interpolator="@android:anim/cycle_interpolator" android:pivotX="50%" android:pivotY="50%" android:startOffset="3800" android:repeatCount="infinite" android:repeatMode="restart" android:toDegrees="360" /> </set>
Step 6.9 – Setting Up SlideUp Animation:
<translate> tag is used in this animation to slide up the ImageView . We have used the following attributes:
duration: The duration in which animation is completed is referred to as duration attribute. It refers to the ideal duration to show the transition on the screen.
fromYDelta: refers to change in Y coordinate to apply at the start of the animation
toYDelta: refers to change in Y coordinate to apply at the end of the animation
fragment_slideup.xml (Create in layout folder):
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" > <ImageView android:id="@+id/imgslideup" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerInParent="true" android:src="@drawable/slide" /> <Button android:id="@+id/btnSlideup" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginBottom="22dp" android:text="Start Animation" android:layout_alignParentBottom="true" android:layout_alignRight="@+id/imgslideup" android:layout_alignEnd="@+id/imgslideup" /> </RelativeLayout>
slideupfragment.java (Create in fragment folder):
package com.example.abhishek.animationexample.fragment; import android.support.v4.app.Fragment; import android.os.Bundle; import android.support.annotation.Nullable; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.animation.Animation; import android.view.animation.AnimationUtils; import android.widget.Button; import android.widget.ImageView; import com.example.abhishek.animationexample.R; /** * Created by abhishek on 27/10/17. */ public class slideupfragment extends Fragment implements Animation.AnimationListener{ @Nullable ImageView imageView; Button btnStart; View view; Animation animSlideup; @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) { view = inflater.inflate(R.layout.fragment_slideup, container, false); imageView = (ImageView) view.findViewById(R.id.imgslideup); btnStart = (Button)view.findViewById(R.id.btnSlideup); animSlideup = AnimationUtils.loadAnimation(getContext(), R.anim.slide_up); animSlideup.setAnimationListener(this); btnStart.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { imageView.startAnimation(animSlideup); } }); return view; } @Override public void onAnimationStart(Animation animation) { } @Override public void onAnimationEnd(Animation animation) { } @Override public void onAnimationRepeat(Animation animation) { } }
slide_up.xml (Create in anim folder):
<?xml version="1.0" encoding="utf-8"?> <set xmlns:android="http://schemas.android.com/apk/res/android" > <translate android:duration="1000" android:fromYDelta="100%" android:toYDelta="0" /> </set>
Step 6.10 – Setting Up SlideDown Animation:
Slide down animation is exactly opposite to slide up animation. You have to interchange android:fromYScale and android:toYScale values.
fragment_slidedown.xml (Create in layout folder):
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" > <ImageView android:id="@+id/imgSlidedown" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerInParent="true" android:src="@drawable/slide" android:visibility="gone" /> <Button android:id="@+id/btnSlidedown" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Start Animation" android:layout_marginRight="44dp" android:layout_marginEnd="44dp" android:layout_marginBottom="38dp" android:layout_alignParentBottom="true" android:layout_alignParentRight="true" android:layout_alignParentEnd="true" /> </RelativeLayout>
slidedownfragment.java (Create in fragment folder):
package com.example.abhishek.animationexample.fragment; import android.support.v4.app.Fragment; import android.os.Bundle; import android.support.annotation.Nullable; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.animation.Animation; import android.view.animation.AnimationUtils; import android.widget.Button; import android.widget.ImageView; import com.example.abhishek.animationexample.R; /** * Created by abhiandroid */ public class slidedownfragment extends Fragment implements Animation.AnimationListener { @Nullable ImageView imageView; Button btnStart; View view; Animation animSlidedown; @Override public View onCreateView(final LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) { view = inflater.inflate(R.layout.fragment_slidedown, container, false); imageView = (ImageView) view.findViewById(R.id.imgSlidedown); btnStart = (Button) view.findViewById(R.id.btnSlidedown); animSlidedown = AnimationUtils.loadAnimation(getContext(), R.anim.slide_down); animSlidedown.setAnimationListener(this); btnStart.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { imageView.setVisibility(View.VISIBLE); imageView.startAnimation(animSlidedown); } }); return view; } @Override public void onAnimationStart(Animation animation) { } @Override public void onAnimationEnd(Animation animation) { } @Override public void onAnimationRepeat(Animation animation) { } }
slide_down.xml(Create animation resource directory in anim folder):
<?xml version="1.0" encoding="utf-8"?> <set xmlns:android="http://schemas.android.com/apk/res/android" > <translate android:duration="1000" android:fromYDelta="0" android:toYDelta="100%" /> </set>
Step 6.11 – Setting Up Swap Animation:
This Animation will create a 3D rotation on the Y axis. The rotation is defined by its start angle and its end angle. Both angles are in degrees. The rotation is performed around a center point on the 2D space, defined by a pair of X and Y coordinates, called centerX and centerY. When the animation starts, a translation on the Z axis (depth) is performed.
fromDegrees: represents the start angle of the 3D rotation
toDegrees: represents the end angle of the 3D rotation
centerX: represents the X center of the 3D rotation
centerY: represents the Y center of the 3D rotation
fragment_swapanimation.xml(Create in layout folder):
<?xml version="1.0" encoding="utf-8"?> <FrameLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/container" android:layout_width="fill_parent" android:layout_height="fill_parent"> <ListView android:id="@android:id/list" android:persistentDrawingCache="animation|scrolling" android:layout_width="fill_parent" android:layout_height="fill_parent" android:layoutAnimation="@anim/layout_bottom_to_top_slide" /> <ImageView android:id="@+id/picture" android:scaleType="fitCenter" android:layout_width="fill_parent" android:layout_height="fill_parent" android:visibility="gone" /> </FrameLayout>
Now create a java class under your main package and name it –
Rotation.java(Create in fragment folder):
package com.example.abhishek.animationexample; import android.graphics.Camera; import android.graphics.Matrix; import android.view.animation.Animation; import android.view.animation.Transformation; public class Rotation extends Animation { private final float mFromDegrees; private final float mToDegrees; private final float mCenterX; private final float mCenterY; private final float mDepthZ; private final boolean mReverse; private Camera mCamera; public Rotation(float fromDegrees, float toDegrees, float centerX, float centerY, float depthZ, boolean reverse) { mFromDegrees = fromDegrees; mToDegrees = toDegrees; mCenterX = centerX; mCenterY = centerY; mDepthZ = depthZ; mReverse = reverse; } @Override public void initialize(int width, int height, int parentWidth, int parentHeight) { super.initialize(width, height, parentWidth, parentHeight); mCamera = new Camera(); } @Override protected void applyTransformation(float interpolatedTime, Transformation t) { final float fromDegrees = mFromDegrees; float degrees = fromDegrees + ((mToDegrees - fromDegrees) * interpolatedTime); final float centerX = mCenterX; final float centerY = mCenterY; final Camera camera = mCamera; final Matrix matrix = t.getMatrix(); camera.save(); if (mReverse) { camera.translate(0.0f, 0.0f, mDepthZ * interpolatedTime); } else { camera.translate(0.0f, 0.0f, mDepthZ * (1.0f - interpolatedTime)); } camera.rotateY(degrees); camera.getMatrix(matrix); camera.restore(); matrix.preTranslate(-centerX, -centerY); matrix.postTranslate(centerX, centerY); } }
swapanimationfragment.java (Create in fragment folder):
position: represents the item that was clicked to show a picture, or -1 to show the list
start: is the start angle at which the rotation must begin
end: is the end angle of the rotation.
The animation listener is used to trigger the next animation
package com.example.abhishek.animationexample.fragment; import android.app.Activity; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.animation.AccelerateInterpolator; import android.view.animation.Animation; import android.view.animation.DecelerateInterpolator; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.ImageView; import android.widget.ListView; import com.example.abhishek.animationexample.R; import com.example.abhishek.animationexample.Rotation; /** * Created by abhiandroid */ public class swapanimationfragment extends Fragment implements AdapterView.OnItemClickListener, View.OnClickListener { private ListView mPhotosList; private ViewGroup mContainer; private ImageView mImageView; // Names of the photos we show in the list private static final String[] PHOTOS_NAMES = new String[]{ "India", "BanglaDesh", "Germany", "Canada" }; // Resource identifiers for the photos we want to display private static final int[] PHOTOS_RESOURCES = new int[]{ R.drawable.india, R.drawable.bangladesh, R.drawable.germany, R.drawable.canada }; View view; @Nullable @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { view = inflater.inflate(R.layout.fragment_swapanimation, container, false); mPhotosList = (ListView) view.findViewById(android.R.id.list); mImageView = (ImageView) view.findViewById(R.id.picture); mContainer = (ViewGroup) view.findViewById(R.id.container); // Prepare the ListView final ArrayAdapter<String> adapter = new ArrayAdapter<String>(getContext(), android.R.layout.simple_list_item_1, PHOTOS_NAMES); mPhotosList.setAdapter(adapter); mPhotosList.setOnItemClickListener(this); // Prepare the ImageView mImageView.setClickable(true); mImageView.setFocusable(true); mImageView.setOnClickListener(this); mContainer.setPersistentDrawingCache(ViewGroup.PERSISTENT_ANIMATION_CACHE); return view; } private void applyRotation(int position, float start, float end) { // Find the center of the container final float centerX = mContainer.getWidth() / 2.0f; final float centerY = mContainer.getHeight() / 2.0f; final Rotation rotation = new Rotation(start, end, centerX, centerY, 310.0f, true); rotation.setDuration(500); rotation.setFillAfter(true); rotation.setInterpolator(new AccelerateInterpolator()); rotation.setAnimationListener(new DisplayNextView(position)); mContainer.startAnimation(rotation); } public void onItemClick(AdapterView parent, View v, int position, long id) { // Pre-load the image then start the animation mImageView.setImageResource(PHOTOS_RESOURCES[position]); applyRotation(position, 0, 90); } public void onClick(View v) { applyRotation(-1, 180, 90); } /** * This class listens for the end of the first half of the animation. * It then posts a new action that effectively swaps the views when the container is rotated 90 degrees and thus invisible. */ private final class DisplayNextView implements Animation.AnimationListener { private final int mPosition; private DisplayNextView(int position) { mPosition = position; } public void onAnimationStart(Animation animation) { } public void onAnimationEnd(Animation animation) { mContainer.post(new SwapViews(mPosition)); } public void onAnimationRepeat(Animation animation) { } } /** * This class is responsible for swapping the views and start the second half of the animation. */ private final class SwapViews implements Runnable { private final int mPosition; public SwapViews(int position) { mPosition = position; } public void run() { final float centerX = mContainer.getWidth() / 2.0f; final float centerY = mContainer.getHeight() / 2.0f; Rotation rotation; if (mPosition > -1) { mPhotosList.setVisibility(View.GONE); mImageView.setVisibility(View.VISIBLE); mImageView.requestFocus(); rotation = new Rotation(90, 180, centerX, centerY, 310.0f, false); } else { mImageView.setVisibility(View.GONE); mPhotosList.setVisibility(View.VISIBLE); mPhotosList.requestFocus(); rotation = new Rotation(90, 0, centerX, centerY, 310.0f, false); } rotation.setDuration(5000); rotation.setFillAfter(true); rotation.setInterpolator(new DecelerateInterpolator()); mContainer.startAnimation(rotation); } } }
res->anim->layout_bottom_to_top_slide.xml:
<?xml version="1.0" encoding="utf-8"?> <layoutAnimation xmlns:android="http://schemas.android.com/apk/res/android" android:delay="30%" android:animationOrder="reverse" android:animation="@anim/slide_right" />
res->anim->slide_right.xml:
<?xml version="1.0" encoding="utf-8"?> <set xmlns:android="http://schemas.android.com/apk/res/android" android:interpolator="@android:anim/accelerate_interpolator"> <translate android:fromXDelta="-100%p" android:toXDelta="0" android:duration="@android:integer/config_shortAnimTime" /> </set>
And in drawable folder download the flags of four countries: India, Bangladesh, Germany, Canada respectively as india.png , bangladesh.png, germany.png,canada.png.
Step 6.12 – Setting Up Together Animation:
Together animation refers to the writing all animations one by one without using android:startOffset(refers to the waiting time before an animation starts. This property is mainly used to perform multiple animations in a sequential manner)
android:fillAfter: this attribute defines whether the view should be visible or not at the end of the animation.We have set its value true in our animation.If it would set to false then element changes comes to its previous state after the animation
android:interpolator: this property refers to the rate of change in animation. You can define your own interpolators using the time as the constraint. In this animation we have used an inbuilt interpolator i.e. linear interpolator
fragment_togetheranimation.xml (Create in layout folder):
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent"> <ImageView android:id="@+id/imgtogether" android:layout_width="200dp" android:layout_height="122dp" android:src="@drawable/together" android:layout_marginTop="156dp" android:layout_alignParentTop="true" android:layout_centerHorizontal="true" /> <Button android:id="@+id/btntogether" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Start" android:layout_marginRight="56dp" android:layout_marginEnd="56dp" android:layout_alignParentBottom="true" android:layout_alignParentRight="true" android:layout_alignParentEnd="true" android:layout_marginBottom="24dp" /> </RelativeLayout>
togetheranimationfragment.java(Create in fragment folder):
package com.example.abhishek.animationexample.fragment; import android.support.v4.app.Fragment; import android.os.Bundle; import android.support.annotation.Nullable; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.animation.Animation; import android.view.animation.AnimationUtils; import android.widget.Button; import android.widget.ImageView; import com.example.abhishek.animationexample.R; /** * Created by abhiandroid */ public class togetheranimationfragment extends Fragment implements Animation.AnimationListener{ @Nullable ImageView imageView; Button btnStart; View view; Animation animTogether; @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) { view = inflater.inflate(R.layout.fragment_togetheranimation, container, false); imageView = (ImageView) view.findViewById(R.id.imgtogether); btnStart = (Button)view.findViewById(R.id.btntogether); animTogether = AnimationUtils.loadAnimation(getContext(), R.anim.together ); animTogether.setAnimationListener(this); btnStart.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { imageView.startAnimation(animTogether); } }); return view; } @Override public void onAnimationStart(Animation animation) { } @Override public void onAnimationEnd(Animation animation) { } @Override public void onAnimationRepeat(Animation animation) { } }
together.xml(Create animation resource directory in anim folder):
<?xml version="1.0" encoding="utf-8"?> <set xmlns:android="http://schemas.android.com/apk/res/android" android:fillAfter="true" android:interpolator="@android:anim/linear_interpolator" > <!-- Move --> <scale xmlns:android="http://schemas.android.com/apk/res/android" android:duration="4000" android:fromXScale="1" android:fromYScale="1" android:pivotX="50%" android:pivotY="50%" android:toXScale="4" android:toYScale="4" > </scale> <!-- Rotate 180 degrees --> <rotate android:duration="500" android:fromDegrees="0" android:pivotX="50%" android:pivotY="50%" android:repeatCount="infinite" android:repeatMode="restart" android:toDegrees="360" /> </set>
Step 6.13 – Setting Up ZoomIn Animation:
For Zoom use <scale> tag . It defines the scaling of the object.It has the following parameters:
android:duration: The duration in which animation is completed is referred to as duration attribute. It refers to the ideal duration to show the transition on the screen.
android:fromXScale : Horizontal scaling factor to apply at the start of the animation.
android:fromYScale: Vertical scaling factor to apply at the start of the animation.
android:toXScale: Horizontal scaling factor to apply at the end of the animation.
android:toYScale: Vertical scaling factor to apply at the end of the animation.
pivotX and pivotY: is the central point of the animation;
android:pivotX=”50%” and android:pivotY = “50%” means the zoom will be started from the center.
For zoom in : fromXScale, fromYScale attributes values must be lesser than toXScale, toYScale
fragment_zoomin.xml(Create in layout folder):
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:gravity="center"> <ImageView android:id="@+id/imgzoomin" android:layout_width="188dp" android:layout_height="150dp" android:src="@drawable/zoom" android:layout_marginLeft="68dp" android:layout_marginStart="68dp" android:layout_marginTop="91dp" android:layout_alignParentTop="true" android:layout_alignParentLeft="true" android:layout_alignParentStart="true" /> <Button android:id="@+id/btnzoomin" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Start ZOOM IN" android:layout_marginBottom="19dp" android:layout_alignParentBottom="true" android:layout_alignParentRight="true" android:layout_alignParentEnd="true" android:layout_marginRight="36dp" android:layout_marginEnd="36dp" /> </RelativeLayout>
zoominfragment.java(Create in fragment folder):
package com.example.abhishek.animationexample.fragment; import android.support.v4.app.Fragment; import android.os.Bundle; import android.support.annotation.Nullable; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.animation.Animation; import android.view.animation.AnimationUtils; import android.widget.Button; import android.widget.ImageView; import com.example.abhishek.animationexample.R; /** * Created by abhiandroid */ public class zoominfragment extends Fragment implements Animation.AnimationListener{ @Nullable ImageView imageView; Button btnStart; View view; Animation animZoomin; @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) { view = inflater.inflate(R.layout.fragment_zoomin, container, false); imageView = (ImageView) view.findViewById(R.id.imgzoomin); btnStart = (Button)view.findViewById(R.id.btnzoomin); animZoomin = AnimationUtils.loadAnimation(getContext(), R.anim.zoom_in ); animZoomin.setAnimationListener(this); btnStart.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { imageView.startAnimation(animZoomin); } }); return view; } @Override public void onAnimationStart(Animation animation) { } @Override public void onAnimationEnd(Animation animation) { } @Override public void onAnimationRepeat(Animation animation) { } }
zoom_in.xml(Create in anim folder):
<?xml version="1.0" encoding="utf-8"?> <set xmlns:android="http://schemas.android.com/apk/res/android" android:fillAfter="true" > <scale xmlns:android="http://schemas.android.com/apk/res/android" android:duration="3500" android:fromXScale="1.0" android:fromYScale="1.0" android:pivotX="80%" android:pivotY="80%" android:toXScale="2.0" android:toYScale="2.0" > </scale> </set>
Step 6.14 – Setting Up ZoomOut Animation:
Zoom out animation is same as zoom in but toXScale, toYScale attributes values are lesser than fromXScale, fromYScale
fragment_zoomout.xml(Create in layout folder):
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:gravity="center"> <ImageView android:id="@+id/imgzoomout" android:layout_width="188dp" android:layout_height="150dp" android:src="@drawable/zoom" android:layout_marginLeft="68dp" android:layout_marginStart="68dp" android:layout_marginTop="91dp" android:layout_alignParentTop="true" android:layout_alignParentLeft="true" android:layout_alignParentStart="true" /> <Button android:id="@+id/btnzoomout" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Start ZOOM OUT" android:layout_marginBottom="19dp" android:layout_alignParentBottom="true" android:layout_alignParentRight="true" android:layout_alignParentEnd="true" android:layout_marginRight="36dp" android:layout_marginEnd="36dp" /> </RelativeLayout>
zoomoutfragment.java(Create in fragment folder):
package com.example.abhishek.animationexample.fragment; import android.support.v4.app.Fragment; import android.os.Bundle; import android.support.annotation.Nullable; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.animation.Animation; import android.view.animation.AnimationUtils; import android.widget.Button; import android.widget.ImageView; import com.example.abhishek.animationexample.R; /** * Created by abhiandroid */ public class zoomoutfragment extends Fragment implements Animation.AnimationListener{ @Nullable ImageView imageView; Button btnStart; View view; Animation animZoomout; @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) { view = inflater.inflate(R.layout.fragment_zoomout, container, false); imageView = (ImageView) view.findViewById(R.id.imgzoomout); btnStart = (Button)view.findViewById(R.id.btnzoomout); animZoomout = AnimationUtils.loadAnimation(getContext(), R.anim.zoom_out ); animZoomout.setAnimationListener(this); btnStart.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { imageView.startAnimation(animZoomout); } }); return view; } @Override public void onAnimationStart(Animation animation) { } @Override public void onAnimationEnd(Animation animation) { } @Override public void onAnimationRepeat(Animation animation) { } }
zoom_out.xml(Create in anim folder):
<?xml version="1.0" encoding="utf-8"?> <set xmlns:android="http://schemas.android.com/apk/res/android" android:fillAfter="true" > <scale xmlns:android="http://schemas.android.com/apk/res/android" android:duration="3500" android:fromXScale="1.0" android:fromYScale="1.0" android:pivotX="50%" android:pivotY="80%" android:toXScale="0.2" android:toYScale="0.2" > </scale> </set>
Output:
Now run the App and open the Navigation Menu. Click on Animation name you want to see to test it.
Premium Project Source Code: