Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android 動畫入門:/View 動畫與屬性動畫的差異

編輯:關於 Android 程式設計

先看一段最基礎的平移動畫:

package com.example.animation; import android.app.Activity; import android.os.Bundle; import android.view.View; import android.view.animation.TranslateAnimation; 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 click(View view){ Toast.makeText(this, "click", Toast.LENGTH_SHORT).show(); } public void move(View view ){ float fromXDelta=0; float toXDelta=0; float fromYDelta=0; float toYDelta=200; TranslateAnimation animation = new TranslateAnimation(fromXDelta, toXDelta, fromYDelta, toYDelta); animation.setDuration(1000); animation.setFillAfter(true); ImageView imageView=(ImageView)findViewById(R.id.imageView); imageView.startAnimation(animation); } }

這屬於傳統的 View 動畫。接著看屬性動畫的寫法。

兩者的關鍵差異在於:View 動畫執行後,圖片雖然移動了,但 View 本身的位置與事件區域並未改變;而屬性動畫則是 View 隨著圖片一起移動。

public void move(View view ){ ImageView imageView=(ImageView)findViewById(R.id.imageView); ObjectAnimator.ofFloat(imageView, "translationY", 0f,200f).setDuration(1000).start(); }

多個動畫同時播放

public void move(View view ){ ImageView imageView=(ImageView)findViewById(R.id.imageView); ObjectAnimator.ofFloat(imageView, "translationY", 0f,200f).setDuration(1000).start(); ObjectAnimator.ofFloat(imageView, "translationX", 0f,200f).setDuration(1000).start(); ObjectAnimator.ofFloat(imageView, "rotation", 0,360f).setDuration(1000).start(); }

Google 也提供了一種更節省系統資源的寫法,用 PropertyValuesHolder 一次驅動多個屬性:

public void move(View view ){ ImageView imageView=(ImageView)findViewById(R.id.imageView); PropertyValuesHolder p1=PropertyValuesHolder.ofFloat("rotation", 0,360f); PropertyValuesHolder p2=PropertyValuesHolder.ofFloat("translationX", 0f,200f); PropertyValuesHolder p3=PropertyValuesHolder.ofFloat("translationY", 0f,200f); ObjectAnimator.ofPropertyValuesHolder(imageView, p1,p2,p3).setDuration(1000).start(); }

此外,Google 還提供了 AnimatorSet,能讓多段動畫依需求排序或並行播放,例如 playTogether() 與 playSequentially():

public void move(View view ){ ImageView imageView=(ImageView)findViewById(R.id.imageView); ObjectAnimator animator1=ObjectAnimator.ofFloat(imageView, "rotation", 0,360f); ObjectAnimator animator2=ObjectAnimator.ofFloat(imageView, "translationX", 0,200f); ObjectAnimator animator3=ObjectAnimator.ofFloat(imageView, "translationY", 0,200f); AnimatorSet set=new AnimatorSet(); //set.playTogether(animator1,animator2,animator3); set.playSequentially(animator1,animator2,animator3); set.setDuration(1000); set.start(); }
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved