Animation trong Android



Animation là tiến trình tạo chuyển động và biến đổi hình dạng.

Animation trong Android là có thể thực hiện theo nhiều cách khác nhau. Trong chương này chúng ta sẽ thảo luận cách dễ nhất và được sử dụng phổ biến nhất để tạo Animation, đó là Tween Animation.

Tween Animation trong Android

Tween Animation nhận một vài tham số như giá trị bắt đầu, giá trị kết thúc, kích cỡ, khoảng thời gian, góc quay, … và thực hiện animation cần thiết trên đối tượng. Nó có thể được áp dụng cho bất kỳ kiểu đối tượng nào. Để thực hiện điều này, Android cung cấp cho chúng ta một lớp Animation.

Để thực hiện Animation trong Android, chúng ta gọi một hàm tĩnh là loadAnimation() của lớp AnimationUtils. Chúng ta sẽ nhận kết quả là một instance của đối tượng Animation. Cú pháp là: −

Animation animation = AnimationUtils.loadAnimation(getApplicationContext(), R.anim.myanimation);

Bạn chú ý tham số thứ hai. Đó là tên của animation xml file của chúng ta. Bạn phải tạo một folder mới là anim dưới thư mục res và tạo một xml file dưới anim này.

Bảng dưới liệt kê một số hàm hữu ích được cung cấp bởi lớp Animation:

Stt Phương thức & Miêu tả
1 start()

Phương thức này bắt đầu Animation

2 setDuration(long duration)

Phương thức này thiết lập khoảng thời gian của một Animation

3 getDuration()

Phương thức này lấy khoảng thời gian đã được thiết lập bởi phương thức trên

4 end()

Phương thức này kết thúc Animation

5 cancel()

Phương thức này hủy bỏ Animation

Để áp dụng Animation cho một đối tượng, chúng ta chỉ cần gọi phương thức startAnimation() của đối tượng đó. Cú pháp là: −

ImageView image1 = (ImageView)findViewById(R.id.imageView1);
image.startAnimation(animation);

Ví dụ

Quảng cáo

Ví dụ sau minh họa sự sử dụng của Animation trong Android. Bạn có thể chọn các kiểu Animation khác nhau từ menu và Animation đã được lựa chọn đó sẽ được áp dụng trên một imageView trên màn hình.

Để thử nghiệm ví dụ, bạn cần chạy nó trên một màn hình mô phỏng Emulator hoặc một thiết bị thực sự.

Đây là nội dung đã sửa đổi của MainActivity.java.

package com.example.sairamkrishna.myapplication;

import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ImageView;
import android.widget.Toast;

public class MainActivity extends Activity {
   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
   }
   
   public void clockwise(View view){
      ImageView image = (ImageView)findViewById(R.id.imageView);
      Animation animation = AnimationUtils.loadAnimation(getApplicationContext(), R.anim.myanimation);
      image.startAnimation(animation);
   }
   
   public void zoom(View view){
      ImageView image = (ImageView)findViewById(R.id.imageView);
      Animation animation1 = AnimationUtils.loadAnimation(getApplicationContext(), R.anim.clockwise);
      image.startAnimation(animation1);
   }
   
   public void fade(View view){
      ImageView image = (ImageView)findViewById(R.id.imageView);
      Animation animation1 = AnimationUtils.loadAnimation(getApplicationContext(), R.anim.fade);
      image.startAnimation(animation1);
   }
   
   public void blink(View view){
      ImageView image = (ImageView)findViewById(R.id.imageView);
      Animation animation1 = AnimationUtils.loadAnimation(getApplicationContext(), R.anim.blink);
      image.startAnimation(animation1);
   }
   
   public void move(View view){
      ImageView image = (ImageView)findViewById(R.id.imageView);
      Animation animation1 = AnimationUtils.loadAnimation(getApplicationContext(), R.anim.move);
      image.startAnimation(animation1);
   }
   
   public void slide(View view){
      ImageView image = (ImageView)findViewById(R.id.imageView);
      Animation animation1 = AnimationUtils.loadAnimation(getApplicationContext(), R.anim.slide);
      image.startAnimation(animation1);
   }
   
   @Override
   public boolean onCreateOptionsMenu(Menu menu) {
      // Inflate the menu; this adds items to the action bar if it is present.
      getMenuInflater().inflate(R.menu.menu_main, menu);
      return true;
   }
   
   @Override
   public boolean onOptionsItemSelected(MenuItem item) {
      // Handle action bar item clicks here. The action bar will
      // automatically handle clicks on the Home/Up button, so long
      // as you specify a parent activity in AndroidManifest.xml.
      
      int id = item.getItemId();
      
      //noinspection SimplifiableIfStatement
      if (id == R.id.action_settings) {
         return true;
      }
      return super.onOptionsItemSelected(item);
   }
}

Đây là nội dung đã sửa đổi của res/layout/activity_main.xml.

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
   xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
   android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
   android:paddingRight="@dimen/activity_horizontal_margin"
   android:paddingTop="@dimen/activity_vertical_margin"
   android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity">
   
   <TextView
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:text="Alert Dialog"
      android:id="@+id/textView"
      android:textSize="35dp"
      android:layout_alignParentTop="true"
      android:layout_centerHorizontal="true" />
      
   <TextView
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:text="Tutorialspoint"
      android:id="@+id/textView2"
      android:textColor="#ff3eff0f"
      android:textSize="35dp"
      android:layout_below="@+id/textView"
      android:layout_centerHorizontal="true" />
      
   <ImageView
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:id="@+id/imageView"
      android:src="@drawable/logo"
      android:layout_below="@+id/textView2"
      android:layout_alignRight="@+id/textView2"
      android:layout_alignEnd="@+id/textView2"
      android:layout_alignLeft="@+id/textView"
      android:layout_alignStart="@+id/textView"/>
      
   <Button
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:text="zoom"
      android:id="@+id/button"
      android:layout_below="@+id/imageView"
      android:layout_alignParentLeft="true"
      android:layout_alignParentStart="true"
      android:layout_marginTop="40dp"
      android:onClick="clockwise"/>
      
   <Button
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:text="clockwise"
      android:id="@+id/button2"
      android:layout_alignTop="@+id/button"
      android:layout_centerHorizontal="true"
      android:onClick="zoom"/>
      
   <Button
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:text="fade"
      android:id="@+id/button3"
      android:layout_alignTop="@+id/button2"
      android:layout_alignParentRight="true"
      android:layout_alignParentEnd="true"
      android:onClick="fade"/>
      
   <Button
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:text="blink"
      android:onClick="blink"
      android:id="@+id/button4"
      android:layout_below="@+id/button"
      android:layout_alignParentLeft="true"
      android:layout_alignParentStart="true" />
      
   <Button
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:text="move"
      android:onClick="move"
      android:id="@+id/button5"
      android:layout_below="@+id/button2"
      android:layout_alignRight="@+id/button2"
      android:layout_alignEnd="@+id/button2"
      android:layout_alignLeft="@+id/button2"
      android:layout_alignStart="@+id/button2" />
      
   <Button
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:text="slide"
      android:onClick="slide"
      android:id="@+id/button6"
      android:layout_below="@+id/button3"
      android:layout_toRightOf="@+id/textView"
      android:layout_toEndOf="@+id/textView" />
      
</RelativeLayout>

Sau đây là nội dung của res/anim/myanimation.xml.

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">

   <scale xmlns:android="http://schemas.android.com/apk/res/android"
      android:fromXScale="0.5"
      android:toXScale="3.0"
      android:fromYScale="0.5"
      android:toYScale="3.0"
      android:duration="5000"
      android:pivotX="50%"
      android:pivotY="50%" >
   </scale>
   
   <scale xmlns:android="http://schemas.android.com/apk/res/android"
      android:startOffset="5000"
      android:fromXScale="3.0"
      android:toXScale="0.5"
      android:fromYScale="3.0"
      android:toYScale="0.5"
      android:duration="5000"
      android:pivotX="50%"
      android:pivotY="50%" >
   </scale>
   
</set>

Sau đây là nội dung của res/anim/clockwise.xml.

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">

   <rotate xmlns:android="http://schemas.android.com/apk/res/android"
      android:fromDegrees="0"
      android:toDegrees="360"
      android:pivotX="50%"
      android:pivotY="50%"
      android:duration="5000" >
   </rotate>
   
   <rotate xmlns:android="http://schemas.android.com/apk/res/android"
      android:startOffset="5000"
      android:fromDegrees="360"
      android:toDegrees="0"
      android:pivotX="50%"
      android:pivotY="50%"
      android:duration="5000" >
   </rotate>
   
</set>

Sau đây là nội dung của res/anim/fade.xml.

Quảng cáo
<?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>

Sau đây là nội dung của res/anim/blink.xml.

<?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="reverse"
      android:repeatCount="infinite"/>
</set>

Sau đây là nội dung của res/anim/move.xml.

<?xml version="1.0" encoding="utf-8"?>
<set
   xmlns:android="http://schemas.android.com/apk/res/android"
   android:interpolator="@android:anim/linear_interpolator"
   android:fillAfter="true">
   
   <translate
      android:fromXDelta="0%p"
      android:toXDelta="75%p"
      android:duration="800" />
</set>

Sau đây là nội dung của res/anim/slide.xml

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android"
   android:fillAfter="true" >
   
   <scale
      android:duration="500"
      android:fromXScale="1.0"
      android:fromYScale="1.0"
      android:interpolator="@android:anim/linear_interpolator"
      android:toXScale="1.0"
      android:toYScale="0.0" />
</set>

Đây là nội dung đã sửa đổi của res/values/string.xml.

<resources>
   <string name="app_name">My Application</string>
   <string name="hello_world">Hello world!</string>
   <string name="action_settings">Settings</string>
</resources>

Tiếp theo là nội dung mặc định của AndroidManifest.xml.

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
   package="com.example.sairamkrishna.myapplication"
   android:versionCode="1"
   android:versionName="1.0" >

   <application
      android:allowBackup="true"
      android:icon="@drawable/ic_launcher"
      android:label="@string/app_name"
      android:theme="@style/AppTheme" >
      
      <activity
         android:name="com.example.animation.MainActivity"
         android:label="@string/app_name" >
      
         <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
         </intent-filter>
      
    </activity>
    
   </application>
</manifest>

Cuối cùng, bạn chạy ứng dụng Android vừa tạo trên

Animation trong Android

Nếu chọn nút ZOOM, nó sẽ hiển thị màn hình sau: −

Animation trong Android

Nếu chọn nút SLIDE, nó sẽ hiển thị màn hình sau:

Animation trong Android

Nếu chọn nút MOVE, nó sẽ hiển thị màn hình sau:

Animation trong Android

Nếu chọn nút CLOCKWISE, nó sẽ hiển thị màn hình sau:

Animation trong Android

Nếu chọn nút FADE, nó sẽ hiển thị màn hình sau:

Animation trong Android

Ghi chú: − Nếu bạn chạy ví dụ trên màn hình mô phỏng Emulator, bạn không thể có một hiệu ứng uyển chuyển. Vì thế bạn nên chạy trên thiết bị Android thực sự.

Đã có app VietJack trên điện thoại, giải bài tập SGK, SBT Soạn văn, Văn mẫu, Thi online, Bài giảng....miễn phí. Tải ngay ứng dụng trên Android và iOS.

Theo dõi chúng tôi miễn phí trên mạng xã hội facebook và youtube:

Các bạn có thể mua thêm khóa học JAVA CORE ONLINE VÀ ỨNG DỤNG cực hay, giúp các bạn vượt qua các dự án trên trường và đi thực tập Java. Khóa học có giá chỉ 300K, nhằm ưu đãi, tạo điều kiện cho sinh viên cho thể mua khóa học.

Nội dung khóa học gồm 16 chuơng và 100 video cực hay, học trực tiếp tại https://www.udemy.com/tu-tin-di-lam-voi-kien-thuc-ve-java-core-toan-tap/ Bạn nào có nhu cầu mua, inbox trực tiếp a Tuyền, cựu sinh viên Bách Khoa K53, fb: https://www.facebook.com/tuyen.vietjack

Follow facebook cá nhân Nguyễn Thanh Tuyền https://www.facebook.com/tuyen.vietjack để tiếp tục theo dõi các loạt bài mới nhất về Java,C,C++,Javascript,HTML,Python,Database,Mobile.... mới nhất của chúng tôi.




Tài liệu giáo viên