Android Animation Example (tween animations)

本文通过一个实例介绍了如何在Android应用中实现淡入、缩放、旋转和平移等常见动画效果,并展示了如何使用AnimationListener监听动画事件。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Android give us the opportunity to add animations in our applications in order to achieve a better sense of the interface quality. There are many animation types but in this tutorial we are going to use tween animations, a widely used type on Views. Tween animation define simple transformations on the components of a View object and can perform series of them. Animations can be performed through either XML or android code, but XML file is recommended because it is more reusable.

In this example we will define animations through a sequence of XML instructions in order to show simple transformations (fade, zoom, rotation and motion). Also, we will learn how to use the AnimationListener class in animations.

 

For this tutorial, we will use the following tools in a Windows 64-bit platform:

  1. JDK 1.7
  2. Eclipse 4.2 Juno
  3. Android SDK 4.4

1. Create a New Android Application Project

Open Eclipse IDE and go to File → New → Project → Android Application Project.

Specify the name of the application, the project and the package and then click Next.

AnimationsProj1

In the next window, the “Create Activity” option should be checked. The new created activity will be the main activity of your project. Then press Next button.

AnimationsProj2

In “Configure Launcher Icon” window you should choose the icon you want to have in your app. We will use the default icon of android, so click Next.

createProject3!

Select the “Blank Activity” option and press Next.

createProject4!

You have to specify a name for the new Activity and a name for the layout description of your app. The .xml file for the layout will automatically be created in the res/layout folder. Then press Finish.

createProject5!

You can see the structure of the project in the next picture.

AnimationsProjStructure

2. Create the layout of the Main Activity

As we mentioned, we want to show four simple transformations, so for each one we will define a Button that enables a specific animation. Also we will add two different contents of View, more specifically a TextView and an ImageView, in which the transformations will be performed.

Open res/layout/activity_main.xml, go to the respective xml tab and paste the following.

activity_main.xml:

01 <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
02    xmlns:tools="http://schemas.android.com/tools"
03    android:layout_width="match_parent"
04    android:layout_height="match_parent"
05    tools:context=".MainActivity" >
06     
07     <Button
08         android:id="@+id/fade"
09         android:layout_width="wrap_content"
10         android:layout_height="wrap_content"
11         android:layout_alignParentLeft="true"
12         android:layout_alignParentTop="true"
13         android:layout_marginLeft="20dp"
14         android:layout_marginTop="20dp"
15         android:text="Fade In" />
16  
17     <Button
18         android:id="@+id/rotate"
19         android:layout_width="wrap_content"
20         android:layout_height="wrap_content"
21         android:layout_alignParentLeft="true"
22         android:layout_below="@+id/fade"
23         android:layout_marginLeft="20dp"
24         android:text="Rotate" />
25      
26      <Button
27         android:id="@+id/move"
28         android:layout_width="wrap_content"
29         android:layout_height="wrap_content"
30         android:layout_alignParentRight="true"
31         android:layout_below="@+id/zoom"
32         android:layout_marginRight="20dp"
33         android:text="Move-Intent" />
34       
35      <Button
36          android:id="@+id/zoom"
37          android:layout_width="wrap_content"
38          android:layout_height="wrap_content"
39          android:layout_above="@+id/rotate"
40          android:layout_alignLeft="@+id/move"
41          android:text="Zoom +/-" />
42      
43      <TextView
44          android:id="@+id/text"
45          android:layout_width="wrap_content"
46          android:layout_height="wrap_content"
47          android:layout_alignParentTop="true"
48          android:layout_centerHorizontal="true"
49          android:layout_marginTop="150dp"
50          android:textAppearance="?android:attr/textAppearanceLarge"
51          android:textStyle="bold"
52          android:text="Fade In Text ..." />
53       
54      <ImageView
55          android:id="@+id/image"
56          android:layout_width="wrap_content"
57          android:layout_height="wrap_content"
58          android:layout_alignParentTop="true"
59          android:layout_centerHorizontal="true"
60          android:layout_marginTop="200dp"
61          android:src="@drawable/ic_launcher" />
62  
63 </RelativeLayout>

3. Create the xml for the animations

We should create XML files which consist of XML notations, in order to specify animations. Each xml file should located into the anim folder of the res directory.

For this reason right click on res folder → New → Folder. Then specify the name and choose the res directory as the parent folder, like in the image below.

AnimationsProjCreate_anim

For every transformation we will create a separate XML file. Firstly, we will create the fade.xml file for defining fade in at an animation, so <alpha> tag is necessary. The attributes android:fromAlpha and android:toAlpha can take values between 0.0 and 1.0 and android:duration defines the time for an animation to be completed.

Right click on res/anim → New → Android XML File. Specify the name and choose alpha as root element.

fadeAnimationsTest

Now go to res/anim/fade.xml file, open it and paste the following.

fade.xml:

1 <?xml version="1.0" encoding="utf-8"?>
2  
3    <alpha xmlns:android="http://schemas.android.com/apk/res/android"
4         android:interpolator="@android:anim/accelerate_interpolator"
5         android:fromAlpha="0.0"
6         android:toAlpha="1.0"
7         android:duration="3000" >
8    </alpha>

Now, we will create the xml file for the zoom. Right click on res/anim → New → Android XML File. Specify the name aszoom and choose set as root element. Then, open res/anim/zoom.xml file and paste the following code.

zoom.xml:

01 <?xml version="1.0" encoding="utf-8"?>
02 <set xmlns:android="http://schemas.android.com/apk/res/android">
03  
04    <scale xmlns:android="http://schemas.android.com/apk/res/android"
05         android:fromXScale="0.5"
06         android:toXScale="2.5"
07         android:fromYScale="0.5"
08         android:toYScale="2.5"
09         android:duration="3000"
10         android:pivotX="50%"
11         android:pivotY="50%" >
12  
13    </scale>
14  
15  
16    <scale xmlns:android="http://schemas.android.com/apk/res/android"
17         android:startOffset="5000"
18         android:fromXScale="2.5"
19         android:toXScale="0.5"
20         android:fromYScale="2.5"
21         android:toYScale="0.5"
22         android:duration="3000"
23         android:pivotX="50%"
24         android:pivotY="50%" >
25  
26    </scale>
27  
28 </set>

As you can see in the code above, we use two XML notations, so we have to use <set> tag. In this code we try to zoom in fist, and then to zoom out. For this reason <scale> tag is used in both situations. We setpivotX="50%" and pivotY="50%" because we want to have zoom from the center of the View object. Also,android:fromXScaleandroid:fromYScaleandroid:toXScale and android:toYScale elements define the start and the end size of the object, when we zoom in and out respectively.

For rotate transformation, <rotate> tag is used. We can specify the type of the rotation (clockwise or anti-clockwise) and the rotation angles by setting the android:fromDegrees and android:toDegrees attributes with the appropriate values. For clockwise rotation we should set positive values to android:fromDegrees and android:toDegrees attributes, while the opposite happens for anti-clockwise rotation.

In the same way, right click on res/anim → New → Android XML File. Specify the name as rotate and choose set as root element. Then, open res/anim/rotate.xml file and paste the following code.

rotate.xml:

01 <?xml version="1.0" encoding="utf-8"?>
02 <set xmlns:android="http://schemas.android.com/apk/res/android">
03  
04    <rotate xmlns:android="http://schemas.android.com/apk/res/android"
05         android:fromDegrees="0"
06         android:toDegrees="360"
07         android:pivotX="50%"
08         android:pivotY="50%"
09         android:duration="1000" >
10  
11    </rotate>
12  
13    <rotate xmlns:android="http://schemas.android.com/apk/res/android"
14         android:startOffset="1500"
15         android:fromDegrees="360"
16         android:toDegrees="0"
17         android:pivotX="50%"
18         android:pivotY="50%"
19         android:duration="1000" >
20  
21    </rotate>
22  
23 </set>

Finally, <translate> tag is used for vertical and/or horizontal motion. In our example we use android:fromXDelta andandroid:toXDelta attributes to define the offset in percentage (%p). The respective attributes (android:fromYDelta andandroid:toYDelta) exist for a vertical movement.

In the same way, right click on res/anim → New → Android XML File. Specify the name as move and choose set as root element. Then, open res/anim/move.xml file and paste the following.

move.xml:

01 <?xml version="1.0" encoding="utf-8"?>
03     android:interpolator="@android:anim/accelerate_interpolator" >
04      
05     <translate  xmlns:android="http://schemas.android.com/apk/res/android"
06         android:fromXDelta="-75%p"
07         android:toXDelta="75%p"
08         android:duration="2000" >
09          
10     </translate>
11      
12      <translate  xmlns:android="http://schemas.android.com/apk/res/android"
13         android:startOffset="800"
14         android:fromXDelta="75%p"
15         android:toXDelta="-75%p"
16         android:duration="2000" >
17          
18     </translate>
19      
20  
21 </set>

It is very important to mention that we can make more complex animations by using a sequence of the above tags-transformations by setting the attributes with the appropriate values. To have this result we must use the <set> tag.

4. Code the Main Activity

In our example, we are going to enable each animation which is defined in the above XML files, by pressing the appropriate Button. Also, we will use a different approach for motion animation. We are going to use an explicit Intentwhich implements the AnimationListener class.

In order to perform animation, the xml animation should be loaded. For this reason loadAnimation() of theAnimationUtils class is called. The loadAnimation() method returns an Animation object. Then, startAnimation()method is called in order to start the instance of that animation object.

Open src/com.javacodegeeks.android.animationstest/MainActivity.java file and paste the code below.

MainActivity.java:

01 package com.javacodegeeks.android.animationstest;
02  
03 import android.os.Bundle;
04 import android.app.Activity;
05 import android.content.Intent;
06 import android.view.View;
07 import android.view.View.OnClickListener;
08 import android.view.animation.Animation;
09 import android.view.animation.AnimationUtils;
10 import android.widget.Button;
11 import android.widget.ImageView;
12 import android.widget.TextView;
13 import android.widget.Toast;
14  
15 public class MainActivity extends Activity {
16  
17     private Button fade;
18     private Button zoom;
19     private Button moveIntent;
20     private Button rotate;
21     private TextView mytext;
22     private ImageView myimage;
23      
24    @Override
25    protected void onCreate(Bundle savedInstanceState) {
26       super.onCreate(savedInstanceState);
27       setContentView(R.layout.activity_main);
28        
29       mytext = (TextView) findViewById(R.id.text);
30       myimage = (ImageView) findViewById(R.id.image);
31        
32       fade = (Button) findViewById(R.id.fade);
33       fade.setOnClickListener(new OnClickListener() {
34          
35         @Override
36         public void onClick(View v) {
37             // TODO Auto-generated method stub
38             fadeAnimation(v);
39         }
40       });
41        
42       zoom = (Button) findViewById(R.id.zoom);
43       zoom.setOnClickListener(new OnClickListener() {
44          
45         @Override
46         public void onClick(View v) {
47             // TODO Auto-generated method stub
48             zoomAnimation(v);
49         }
50       });
51        
52       moveIntent = (Button) findViewById(R.id.move);
53       moveIntent.setOnClickListener(new OnClickListener() {
54          
55         @Override
56         public void onClick(View v) {
57             // TODO Auto-generated method stub
58             moveAnimation(v);
59         }
60       });
61        
62       rotate = (Button) findViewById(R.id.rotate);
63       rotate.setOnClickListener(new OnClickListener() {
64          
65         @Override
66         public void onClick(View v) {
67             // TODO Auto-generated method stub
68             rotateAnimation(v);
69         }
70       });
71    }
72  
73    private void fadeAnimation(View view) {
74        Animation animation = AnimationUtils.loadAnimation(getApplicationContext(), R.anim.fade);
75        mytext.startAnimation(animation);
76    }
77     
78    private void zoomAnimation(View view) {
79        Animation animation = AnimationUtils.loadAnimation(getApplicationContext(), R.anim.zoom);
80        myimage.startAnimation(animation);
81    }
82     
83    private void rotateAnimation(View view) {
84        Animation animation = AnimationUtils.loadAnimation(getApplicationContext(), R.anim.rotate);
85        myimage.startAnimation(animation);
86    }
87     
88    private void moveAnimation(View view) {
89        try{
90             Intent intent = new Intent(this, MoveActivity.class);
91             startActivity(intent);
92        }catch(Exception e) {
93            Toast.makeText(getApplicationContext(), "Error with the Intent",
94                    Toast.LENGTH_SHORT).show();
95            e.printStackTrace();
96        }
97    }
98  
99 }

5. Code the explicit Intent with animation listener

This Activity will implement the AnimationListener, which receives notifications when animation events occur. WhenAnimationListener is used, we should override onAnimationStart()onAnimationEnd() and onAnimationRepeat()functions. It is important to mention that AnimationListener is optional, because we can perform an animation by using the above way that we showned.

Right click on src/com.javacodegeeks.android.animationstest package → New → Class and then specify the name and the new file, as shown in the next picture.

MoveActcreateClass

Now open src/com.javacodegeeks.android.animationstest/MoveActivity.java file and paste the following.

MoveActivity.java:

01 package com.javacodegeeks.android.animationstest;
02  
03 import android.app.Activity;
04 import android.os.Bundle;
05 import android.view.View;
06 import android.view.View.OnClickListener;
07 import android.view.animation.Animation;
08 import android.view.animation.Animation.AnimationListener;
09 import android.view.animation.AnimationUtils;
10 import android.widget.Button;
11 import android.widget.TextView;
12 import android.widget.Toast;
13  
14 public class MoveActivity extends Activity implements AnimationListener {
15  
16     private TextView movetxt;
17     private Button startBtn;
18      
19     private Animation animation;
20      
21     protected void onCreate(Bundle savedInstanceState) {
22         // TODO Auto-generated method stub
23         super.onCreate(savedInstanceState);
24         setContentView(R.layout.move_view);
25   
26         // load the animation
27         animation = AnimationUtils.loadAnimation(getApplicationContext(), R.anim.move);
28           
29         // set animation listener
30         animation.setAnimationListener(this);
31  
32         movetxt = (TextView) findViewById(R.id.moveText);
33         startBtn = (Button) findViewById(R.id.start);
34         startBtn.setOnClickListener(new OnClickListener() {
35   
36             @Override
37             public void onClick(View v) {
38                 // start the animation
39                 movetxt.startAnimation(animation);
40             }
41         });
42   
43     }
44     @Override
45     public void onAnimationEnd(Animation an) {
46         // when animation ends
47          if (an == animation) {
48                 Toast.makeText(getApplicationContext(), "Animation Stopped",
49                         Toast.LENGTH_SHORT).show();
50          }
51     }
52  
53     @Override
54     public void onAnimationRepeat(Animation an) {
55         // if the animation repeats
56         if (an == animation) {
57             Toast.makeText(getApplicationContext(), "Animation Repeated",
58                     Toast.LENGTH_SHORT).show();
59         }
60     }
61  
62     @Override
63     public void onAnimationStart(Animation an) {
64         // when the animation is started
65         if (an == animation) {
66             Toast.makeText(getApplicationContext(), "Animation Started",
67                     Toast.LENGTH_SHORT).show();
68         }
69     }
70  
71 }

6. Create the layout of the explicit Intent

The interface of the MoveActivity will be very simple. We want to have a Button, which indicates the start of the animation, and a TextView that will be for the performance of the animation.

To create the file for the layout, right click on res/layout → New → Android XML File. Specify the name as move_viewand choose LinearLayout as the root element.

move_viewAnimationTest

Open res/layout/move_view.xml, go to the xml tab and paste the following.

move_view.xml:

01 <?xml version="1.0" encoding="utf-8"?>
02 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
03     android:layout_width="match_parent"
04     android:layout_height="match_parent"
05     android:orientation="vertical" >
06  
07      <TextView
08          android:id="@+id/moveText"
09          android:layout_width="wrap_content"
10          android:layout_height="wrap_content"
11          android:layout_marginTop="20dp"
12          android:text="Javacodegeeks"
13          android:textAppearance="?android:attr/textAppearanceLarge"
14          android:textStyle="bold" />
15  
16      <Button
17          android:id="@+id/start"
18          android:layout_width="wrap_content"
19          android:layout_height="wrap_content"
20          android:layout_marginTop="20dp"
21          android:text="Start the animation" />
22  
23 </LinearLayout>

7. Define the new Activity

Now we have to define the MoveActivity in our AndroidManifest file.

Open AndroidManifest.xml file and go to the respective xml tab. Then paste the code below.

AndroidManifest.xml:

01 <?xml version="1.0" encoding="utf-8"?>
02 <manifest xmlns:android="http://schemas.android.com/apk/res/android"
03     package="com.javacodegeeks.android.animationstest"
04     android:versionCode="1"
05     android:versionName="1.0" >
06  
07     <uses-sdk
08         android:minSdkVersion="8"
09         android:targetSdkVersion="19" />
10  
11     <application
12         android:allowBackup="true"
13         android:icon="@drawable/ic_launcher"
14         android:label="@string/app_name"
15         android:theme="@style/AppTheme" >
16         <activity
17             android:name="com.javacodegeeks.android.animationstest.MainActivity"
18             android:label="@string/app_name" >
19             <intent-filter>
20                 <action android:name="android.intent.action.MAIN" />
21  
22                 <category android:name="android.intent.category.LAUNCHER" />
23             </intent-filter>
24         </activity>
25         <activity
26              android:name="com.javacodegeeks.android.animationstest.MoveActivity"
27             android:label="AnimationsTest: Move-Intent" >
28              
29         </activity>
30     </application>
31  
32 </manifest>

8. Run the application

To run our application, right click on our project → Run as → Android Application. The AVD will appear with the app loaded, as you can see in the picture below.

AVDAnimationsTest1

To see how this application works, we will show some instances of the animations.

Lets press “Fade In” button. As you can see in the next image, the TextView “Fade In Text…” is fading in.

AVDAnimationsTest2

If we press the “Zoom +/-” button, the image will zoom in and then it will zoom out until it reaches it’s original size.

AVDAnimationsTest3

In parallel if we click the “Rotate” button, the image will start rotate clockwise and then anti-clockwise. In the next picture you can see an instance of the rotation of the ImageView.

AVDAnimationsTest4

Now lets press “Move-Intent” button. The MoveActivity of the explicit Intent will launch.

AVDAnimationsTest5

If we press the “Start Animation” button, the text will begin to move horizontally and the onAnimationStart() method will be called.

AVDAnimationsTest6

When the motion of the text stops, the onAnimationEnd() method is called by the AnimationListener, as you can see in the image below.

AVDAnimationsTest7

Download Eclipse Project

This was an example of Animation in Android. Download the Eclipse Project of this example: AnimationsTest.zip

From:http://examples.javacodegeeks.com/android/core/animation/android-animation-example/




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值