Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
您现在的位置: Android教程網 >> Android系統教程 >  >> Android 技術 >> Android 開發 >> 進階開發

Android Animation 動畫的兩種實作方式

編輯:進階開發

Android 提供兩條建立動畫的路徑:在 XML 中宣告,或直接在程式碼中組出物件。兩者效果相同,取決於你希望調整的時機。本文以 RotateAnimation 為例示範,其他如 ScaleAnimation、AlphaAnimation、TranslateAnimation 的原理完全一致。

方法一:在 XML 中定義動畫

於 res/anim/ 下新增檔案,例如 my_rotate_action.xml:

<?XML version="1.0" encoding="utf-8"?>
<set xmlns:android="https://schemas.android.com/apk/res/android">
    <rotate
        android:interpolator="@android:anim/accelerate_decelerate_interpolator"
        android:fromDegrees="0"
        android:toDegrees="+360"
        android:duration="3000" />
</set>

各屬性說明:

  • interpolator:指定插入器,用來控制動畫的速度變化曲線
  • fromDegrees:動畫起始時物件的角度
  • toDegrees:動畫結束時物件旋轉到的角度,正值代表順時針
  • duration:動畫持續時間,單位為毫秒

使用時透過 AnimationUtils.loadAnimation() 載入,效果是按下按鈕後 TextView 旋轉一週:

package com.ray.animation;

import android.app.Activity;
import android.os.Bundle;
import android.view.VIEw;
import android.view.VIEw.OnClickListener;
import android.vIEw.animation.Animation;
import android.vIEw.animation.AnimationUtils;
import android.widget.Button;

public class TestAnimation extends Activity implements OnClickListener {

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        Button btn = (Button) findViewById(R.id.Button01);
        btn.setOnClickListener(this);
    }

    @Override
    public void onClick(VIEw v) {
        Animation anim = AnimationUtils.loadAnimation(this, R.anim.my_rotate_action);
        findViewById(R.id.TextVIEw01).startAnimation(anim);
    }
}

方法二:直接在程式碼中定義

package com.ray.animation;

import android.app.Activity;
import android.os.Bundle;
import android.view.VIEw;
import android.view.VIEw.OnClickListener;
import android.vIEw.animation.AccelerateDecelerateInterpolator;
import android.vIEw.animation.Animation;
import android.vIEw.animation.RotateAnimation;
import android.widget.Button;

public class TestAnimation extends Activity implements OnClickListener {

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        Button btn = (Button) findViewById(R.id.Button);
        btn.setOnClickListener(this);
    }

    public void onClick(VIEw v) {
        Animation anim = new RotateAnimation(0.0f, +360.0f);
        anim.setInterpolator(new AccelerateDecelerateInterpolator());
        anim.setDuration(3000);
        findViewById(R.id.TextVIEw01).startAnimation(anim);
    }
}

該怎麼選

寫在 XML 的好處是動畫參數與版面、邏輯分離,設計人員可以直接調整曲線與時間而不必碰 Java 程式碼,也便於同一段動畫在多處重複使用。程式碼方式則在需要「依執行期狀態決定參數」時更靈活,例如依目前角度做相對旋轉、依資料長度決定 Duration。

最後提醒兩點:<set> 標籤可以包多個動畫並用 android:startOffset 安排先後順序,做出序列動畫;另外 Tween Animation 只是視覺上的位移,並未真正改變 View 的位置與事件觸發範圍,若需要真正的位置變更,應改用屬性動畫(Property Animation)API。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved