Android Animation動畫(Frame-By-Frame Animations 、Tween Animations 、Property Animation)的詳解


轉載請備註出自於:http://blog.csdn.net/qq_22118507/article/details/51438850


Contents:

  • Animations

  • Tween Animations

  • AnimationSet

  • Interpolator

  • Frame-By-Frame Animations

  • LayoutAnimationsController

  • AnimationListener

 


 Animations

一、Animations介紹

Animations是一個實現android UI界面動畫效果的APIAnimations提供了一系列的動畫效果,可以進行旋轉、縮放、淡入淡出等,這些效果可以應用在絕大多數的控件中。 

二、Animations的分類

Animations從總體上可以分爲三大類:

1.Tweened Animations:該類Animations提供了旋轉、移動、伸展和淡出等效果。Alpha——淡入淡出,Scale——縮放效果,Rotate——旋轉,Translate——移動效果。

2.Frame-by-frame Animations:這一類Animations可以創建一個Drawable序列,這些Drawable可以按照指定的時間間歇一個一個的顯示。

      3.property Animations:屬性動畫,改變控件的屬性

三、Animations的使用方法(代碼中使用)

Animations extends Object implements Cloneable 

 使用TweenedAnimations的步驟:

1.創建一個AnimationSet對象(Animation子類);

2.增加需要創建相應的Animation對象;

3.更加項目的需求,爲Animation對象設置相應的數據;

4.Animatin對象添加到AnimationSet對象當中;

5.使用控件對象開始執行AnimationSet


  Tweened Animations的子類
  1、AlphaAnimations:淡入淡出效果動畫
  2、ScaleAnimations:縮放效果動畫
  3、RotateAnimations:旋轉效果動畫
  4、TranslateAnimations:移動效果動畫


四、具體實現

1main.xml

<?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

    android:layout_width="fill_parent"

    android:layout_height="fill_parent"

    android:orientation="vertical" >

 

    <LinearLayout

        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:orientation="horizontal" >

         <Button

            android:id="@+id/rotateButton"

            android:layout_width="wrap_content"

            android:layout_height="wrap_content"

            android:text="旋轉" />

         <Button

            android:id="@+id/scaleButton"

            android:layout_width="wrap_content"

            android:layout_height="wrap_content"

            android:text="縮放" />

         <Button

            android:id="@+id/alphaButton"

            android:layout_width="wrap_content"

            android:layout_height="wrap_content"

            android:text="淡入淡出" />

         <Button

            android:id="@+id/translateButton"

            android:layout_width="wrap_content"

            android:layout_height="wrap_content"

            android:text="移動" />

    </LinearLayout>

     <LinearLayout

        android:layout_width="fill_parent"

        android:layout_height="fill_parent"

        android:orientation="vertical" >

         <ImageView

            android:id="@+id/image"

            android:layout_width="wrap_content"

            android:layout_height="wrap_content"

            android:layout_centerInParent="true"

            android:src="@drawable/an" />

    </LinearLayout>

 </LinearLayout>

2.java文件

importandroid.app.Activity;

importandroid.os.Bundle;

importandroid.view.View;

importandroid.view.View.OnClickListener;

import android.view.animation.AlphaAnimation;

import android.view.animation.Animation;

importandroid.view.animation.AnimationSet;

importandroid.view.animation.RotateAnimation;

importandroid.view.animation.ScaleAnimation;

import android.view.animation.TranslateAnimation;

importandroid.widget.Button;

importandroid.widget.ImageView;

public class Animation1Activity extends Activity {

    private Button rotateButton = null;

    private Button scaleButton = null;

    private Button alphaButton = null;

    private Button translateButton = null;

    private ImageView image = null;

    @Override

    public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.main);

       

        rotateButton = (Button)findViewById(R.id.rotateButton);

        scaleButton = (Button)findViewById(R.id.scaleButton);

        alphaButton = (Button)findViewById(R.id.alphaButton);

        translateButton = (Button)findViewById(R.id.translateButton);

        image = (ImageView)findViewById(R.id.image);

     

        rotateButton.setOnClickListener(newRotateButtonListener());

        scaleButton.setOnClickListener(newScaleButtonListener());

        alphaButton.setOnClickListener(newAlphaButtonListener());

        translateButton.setOnClickListener(

           new TranslateButtonListener());

    }

    class AlphaButtonListener implementsOnClickListener{

       public void onClick(View v) {

           //創建一個AnimationSet對象,參數爲Boolean型,

           //true表示使用Animationinterpolatorfalse則是使用自己的

           AnimationSet animationSet = new AnimationSet(true);

           //創建一個AlphaAnimation對象,參數從完全的透明度,到完全的不透明

           AlphaAnimation alphaAnimation = new AlphaAnimation(1, 0);

           //設置動畫執行的時間

           alphaAnimation.setDuration(500);

           //alphaAnimation對象添加到AnimationSet當中

           animationSet.addAnimation(alphaAnimation);

           //使用ImageViewstartAnimation方法執行動畫

           image.startAnimation(animationSet);

       }

    }

    class RotateButtonListener implementsOnClickListener{

       public void onClick(View v) {

           AnimationSet animationSet = new AnimationSet(true);

           //參數1:從哪個旋轉角度開始

           //參數2:轉到什麼角度

           //4個參數用於設置圍繞着旋轉的圓的圓心在哪裏

           //參數3:確定x軸座標的類型,有ABSOLUT絕對座標、RELATIVE_TO_SELF相對於自身座標、RELATIVE_TO_PARENT相對於父控件的座標

           //參數4x軸的值,0.5f表明是以自身這個控件的一半長度爲x

           //參數5:確定y軸座標的類型

           //參數6y軸的值,0.5f表明是以自身這個控件的一半長度爲x

           RotateAnimation rotateAnimation = new RotateAnimation(0, 360,

                  Animation.RELATIVE_TO_SELF,0.5f,

                  Animation.RELATIVE_TO_SELF,0.5f);

           rotateAnimation.setDuration(1000);

           animationSet.addAnimation(rotateAnimation);

           image.startAnimation(animationSet);

       }

    }

    class ScaleButtonListener implementsOnClickListener{

       public void onClick(View v) {

           AnimationSet animationSet = new AnimationSet(true);

           //參數1x軸的初始值

           //參數2x軸收縮後的值

           //參數3y軸的初始值

           //參數4y軸收縮後的值

           //參數5:確定x軸座標的類型

           //參數6x軸的值,0.5f表明是以自身這個控件的一半長度爲x

           //參數7:確定y軸座標的類型

           //參數8y軸的值,0.5f表明是以自身這個控件的一半長度爲x

           ScaleAnimation scaleAnimation = new ScaleAnimation(

                  0, 0.1f,0,0.1f,

                  Animation.RELATIVE_TO_SELF,0.5f,

                  Animation.RELATIVE_TO_SELF,0.5f);

           scaleAnimation.setDuration(1000);

           animationSet.addAnimation(scaleAnimation);

           image.startAnimation(animationSet);

       }

    }

    class TranslateButtonListener implementsOnClickListener{

       public void onClick(View v) {

           AnimationSet animationSet = new AnimationSet(true);

           //參數12x軸的開始位置

           //參數34y軸的開始位置

           //參數56x軸的結束位置

           //參數78x軸的結束位置

           TranslateAnimation translateAnimation =

              new TranslateAnimation(

                  Animation.RELATIVE_TO_SELF,0f,

                  Animation.RELATIVE_TO_SELF,0.5f,

                  Animation.RELATIVE_TO_SELF,0f,

                  Animation.RELATIVE_TO_SELF,0.5f);

           translateAnimation.setDuration(1000);

           animationSet.addAnimation(translateAnimation);

           image.startAnimation(animationSet);

       }

    }

}

 

Tween Animations的通用方法

  1、setDuration(long durationMills)  設置動畫持續時間(單位:毫秒)
  
  2、setFillAfter(Boolean fillAfter)  如果fillAfter的值爲true,則動畫執行後,控件將停留在執行結束的狀態
  
  3、setFillBefore(Boolean fillBefore)  如果fillBefore的值爲true,則動畫執行後,控件將回到動畫執行之前的狀態
  
  4、setStartOffSet(long startOffSet) 設置動畫執行之前的等待時間
  
  5、setRepeatCount(int repeatCount) 設置動畫重複執行的次數


    6、setInterpolator(Interpolator i):設置動畫的變化速度

    7、setInterpolator(new AccelerateDecelerateInterpolator()):先加速,後減速

    8、setInterpolator(new AccelerateInterpolator()):加速
    9、setInterpolator(new DecelerateInterpolator()):減速
    10、setInterpolator(new CycleInterpolator()):動畫循環播放特定次數,速率改變沿着正弦曲線
    11、setInterpolator(new LinearInterpolator()):勻速

 在代碼中使用Animations可以很方便的調試、運行,但是代碼的可重用性差,重複代碼多。同樣可以在xml文件中配置Animations,這樣做可維護性變高了,只不過不容易進行調試。

一、在xml中使用Animations步驟

       1.res文件夾下建立一個anim文件夾;

       2.創建xml文件,並首先加入set標籤,更改標籤如下:

<?xml version="1.0" encoding="utf-8"?>

<set xmlns:android="http://schemas.android.com/apk/res/android"

    android:interpolator="@android:anim/accelerate_interpolator">

</set>

3.在該標籤當中加入rotatealphascale或者translate標籤;

<alpha

        android:fromAlpha="1.0"

        android:toAlpha="0.0"

        android:startOffset="500"

        android:duration="500"/>

4.在代碼當中使用AnimationUtils當中裝載xml文件,並生成Animation對象。因爲AnimationAnimationSet的子類,所以向上轉型,用Animation對象接收。

Animation animation = AnimationUtils.loadAnimation(

                  Animation1Activity.this, R.anim.alpha);

           // 啓動動畫

           image.startAnimation(animation);

二、具體實現

 1、  alpha.xml

<?xml version="1.0" encoding="utf-8"?>

<set xmlns:android="http://schemas.android.com/apk/res/android"

    android:interpolator="@android:anim/accelerate_interpolator">

    <!-- fromAlphatoAlpha是起始透明度和結束時透明度 -->

    <alpha

        android:fromAlpha="1.0"

        android:toAlpha="0.0"

        android:startOffset="500"

        android:duration="500"/>

</set>

2、  rotate.xml

 

<?xml version="1.0" encoding="utf-8"?>

<set xmlns:android="http://schemas.android.com/apk/res/android"

    android:interpolator="@android:anim/accelerate_interpolator">

    <!--

      (負數fromDegrees——toDegrees正數:順時針旋轉)

         (負數fromDegrees——toDegrees負數:逆時針旋轉)

         (正數fromDegrees——toDegrees正數:順時針旋轉)

         (正數fromDegrees——toDegrees負數:逆時針旋轉)

        toDegrees屬性爲動畫結束時物件旋轉的角度可以大於360度

        fromDegrees:開始的角度

        toDegrees:結束的角度

        pivotX:用於設置旋轉時的x軸座標

        

           1)當值爲"50",表示使用絕對位置定位

           2)當值爲"50%",表示使用相對於控件本身定位

           3)當值爲"50%p",表示使用相對於控件的父控件定位

        pivotY:用於設置旋轉時的y軸座標

      -->

    <rotate

        android:fromDegrees="0"

        android:toDegrees="+360"

        android:pivotX="50%"

        android:pivotY="50%"

        android:duration="1000"/>

</set>

3、  scale.xml

<?xml version="1.0" encoding="utf-8"?>

<set xmlns:android="http://schemas.android.com/apk/res/android"

    android:interpolator="@android:anim/accelerate_interpolator">

   <!--

       起始x軸座標

           x軸座標

           y軸座標

           y軸座標

           軸的座標

           軸的座標

     -->

   <scale

       android:fromXScale="1.0"

       android:toXScale="0.0"

       android:fromYScale="1.0"

       android:toYScale="0.0"

       android:pivotX="50%"

       android:pivotY="50%"

       android:duration="1000"/>

</set>

 

4、  translate.xml

<?xml version="1.0" encoding="utf-8"?>

<set xmlns:android="http://schemas.android.com/apk/res/android"

    android:interpolator="@android:anim/accelerate_interpolator">

    <!--

           x軸座標

           x軸座標

           y軸座標

           y軸座標

      -->

    <translate

        android:fromXDelta="0%"

        android:toXDelta="100%"

        android:fromYDelta="0%"

        android:toYDelta="100%"

        android:duration="2000"/>

</set>

 

5、  .java文件

importandroid.app.Activity;

importandroid.os.Bundle;

importandroid.view.View;

importandroid.view.View.OnClickListener;

import android.view.animation.Animation;

importandroid.view.animation.AnimationUtils;

import android.widget.Button;

import android.widget.ImageView;

 

public class Animation1Activity extends Activity {

    private Button rotateButton = null;

    private Button scaleButton = null;

    private Button alphaButton = null;

    private Button translateButton = null;

    private ImageView image = null;

 

    @Override

    public void onCreate(Bundle savedInstanceState) {

       super.onCreate(savedInstanceState);

       setContentView(R.layout.main);

 

       rotateButton = (Button) findViewById(R.id.rotateButton);

       scaleButton = (Button) findViewById(R.id.scaleButton);

       alphaButton = (Button) findViewById(R.id.alphaButton);

       translateButton = (Button) findViewById(R.id.translateButton);

       image = (ImageView) findViewById(R.id.image);

 

       rotateButton.setOnClickListener(newRotateButtonListener());

       scaleButton.setOnClickListener(newScaleButtonListener());

       alphaButton.setOnClickListener(newAlphaButtonListener());

       translateButton.setOnClickListener(newTranslateButtonListener());

    }

 

    class AlphaButtonListener implementsOnClickListener {

       public void onClick(View v) {

           // 使用AnimationUtils裝載動畫配置文件

           Animation animation = AnimationUtils.loadAnimation(

                  Animation1Activity.this, R.anim.alpha);

           // 啓動動畫

           image.startAnimation(animation);

       }

    }

 

    class RotateButtonListener implementsOnClickListener {

       public void onClick(View v) {

           Animation animation = AnimationUtils.loadAnimation(

                  Animation1Activity.this, R.anim.rotate);

           image.startAnimation(animation);

       }

    }

 

    class ScaleButtonListener implementsOnClickListener {

       public void onClick(View v) {

           Animation animation = AnimationUtils.loadAnimation(

                  Animation1Activity.this, R.anim.scale);

           image.startAnimation(animation);

       }

    }

 

    class TranslateButtonListener implementsOnClickListener {

       public void onClick(View v) {

           Animation animation = AnimationUtils.loadAnimation(Animation1Activity.this, R.anim.translate);

           image.startAnimation(animation);

       }

    }

}

 

AnimationSet的具體使用方法

 

       1.AnimationSetAnimation的子類;

 

       2.一個AnimationSet包含了一系列的Animation

 

       3.針對AnimationSet設置一些Animation的常見屬性(如startOffsetduration等),可以被包含在AnimationSet當中的Animation集成;

 

例:一個AnimationSet中有兩個Animation,效果疊加

 

第一種方法:

 

doubleani.xml

 

<?xml version="1.0" encoding="utf-8"?>

<set xmlns:android="http://schemas.android.com/apk/res/android"

    android:interpolator="@android:anim/accelerate_interpolator"

    android:shareInterpolator="true">

    <!-- fromAlphatoAlpha是起始透明度和結束時透明度 -->

    <alpha

        android:fromAlpha="1.0"

        android:toAlpha="0.0"

        android:startOffset="500"

        android:duration="500"/>

    <translate

        android:fromXDelta="0%"

        android:toXDelta="100%"

        android:fromYDelta="0%"

        android:toYDelta="100%"

        android:duration="2000"/>

</set>

 

.java文件中

 

classDoubleButtonListener implements OnClickListener {

       public void onClick(View v) {

           // 使用AnimationUtils裝載動畫配置文件

           Animation animation = AnimationUtils.loadAnimation(

                  Animation2Activity.this, R.anim. doubleani);

           // 啓動動畫

           image.startAnimation(animation);

       }

    }

 

第二種方法:

 

.java文件中

 

classDoubleButtonListener implements OnClickListener {

       public void onClick(View v) {

           AnimationSet animationSet = new AnimationSet(true);

           AlphaAnimation alphaAnimation = new AlphaAnimation(1, 0);

           RotateAnimation rotateAnimation = new RotateAnimation(0, 360,

                  Animation.RELATIVE_TO_SELF,0.5f,

                  Animation.RELATIVE_TO_SELF,0.5f);

           rotateAnimation.setDuration(1000);

           animationSet.addAnimation(rotateAnimation);

           animationSet.addAnimation(alphaAnimation);

           image.startAnimation(animationSet);

 

       }

    }

 

Interpolator的具體使用方法

 

      我們可以爲每一個動畫設置動畫插入器,Android自帶的幾種動畫插入器:

AccelerateInterpolator           

加速,開始時慢中間加速

DecelerateInterpolator

減速,開始時快然後減速

AccelerateDecelerateInterolator

先加速後減速,開始結束時慢,中間加速

AnticipateInterpolator

反向,先向相反方向改變一段再加速播放

AnticipateOvershootInterpolator

反向加超越,先向相反方向改變,再加速播放,會超出目的值然後緩慢移動至目的值

BounceInterpolator

跳躍,快到目的值時值會跳躍,如目的值100,後面的值可能依次爲85,77,70,80,90,100

CycleIinterpolator

循環,動畫循環一定次數,值的改變爲一正弦函數:Math.sin(2* mCycles* Math.PI* input)

LinearInterpolator

線性,線性均勻改變

OvershottInterpolator

超越,最後超出目的值然後緩慢改變到目的值


分爲以下幾種情況:

1、在set標籤中

<set xmlns:android="http://schemas.android.com/apk/res/android"

    android:interpolator="@android:anim/accelerate_interpolator"/>

2、如果在一個set標籤中包含多個動畫效果,如果想讓這些動畫效果共享一個Interpolator

    android:shareInterpolator="true"

3、如果不想共享一個interpolator,則設置android:shareInterpolator="true"並且需要在每一個動畫效果處添加interpolator

<alpha

        android:interpolator="@android:anim/accelerate_decelerate_interpolator"

        android:fromAlpha="1.0"

        android:toAlpha="0.0"

        android:startOffset="500"

        android:duration="500"/>

 

4、如果是在代碼上設置共享一個interpolator則可以在AnimationSet設置interpolator

 

AnimationSet animationSet = newAnimationSet(true);

animationSet.setInterpolator(new AccelerateInterpolator());

 

5、如果不設置共享一個interpolator則可以在每一個Animation對象上面設置interpolator

 

AnimationSet animationSet = newAnimationSet(false);

alphaAnimation.setInterpolator(new AccelerateInterpolator());

rotateAnimation.setInterpolator(new DecelerateInterpolator());

 


Frame-By-Frame Animations的使用方法

 

       Frame-By-Frame Animations是一幀一幀的格式顯示動畫效果。類似於電影膠片拍攝的手法。

 main.xml

<?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

    android:orientation="vertical"

    android:layout_width="fill_parent"

    android:layout_height="fill_parent">

    <LinearLayout

        android:orientation="horizontal"

        android:layout_height="wrap_content"

        android:layout_width="wrap_content">

       <Button

           android:id="@+id/button"

               android:layout_width="wrap_content"

               android:layout_height="wrap_content"

               android:text="運動"/>

    </LinearLayout>

    <LinearLayout

        android:orientation="vertical"

        android:layout_width="fill_parent"

        android:layout_height="fill_parent">

       <ImageView

           android:id="@+id/image"

            android:layout_width="wrap_content"

            android:layout_height="wrap_content"

            android:layout_centerInParent="true"/>

    </LinearLayout>

</LinearLayout>

 

3、anim.xml

<?xml version="1.0" encoding="utf-8"?>

<animation-list xmlns:android="http://schemas.android.com/apk/res/android"

    android:oneshot="false">

    <item android:drawable="@drawable/a_01" android:duration="50"/>

    <item android:drawable="@drawable/a_02" android:duration="50"/>

    <item android:drawable="@drawable/a_03" android:duration="50"/>

    <item android:drawable="@drawable/a_04" android:duration="50"/>

    <item android:drawable="@drawable/a_05" android:duration="50"/>

    <item android:drawable="@drawable/a_06" android:duration="50"/>

</animation-list>

 

4.java文件

importandroid.app.Activity;

importandroid.graphics.drawable.AnimationDrawable;

importandroid.os.Bundle;

importandroid.view.View;

importandroid.view.View.OnClickListener;

importandroid.widget.Button;

importandroid.widget.ImageView;

public class AnimationsActivity extends Activity {

    private Button button = null;

    private ImageView imageView = null;

    @Override

    public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.main);

        button = (Button)findViewById(R.id.button);

        imageView = (ImageView)findViewById(R.id.image);

        button.setOnClickListener(newButtonListener());

    }

    class ButtonListener implementsOnClickListener{

       public void onClick(View v) {

           imageView.setBackgroundResource(R.anim.anim);

           AnimationDrawable animationDrawable = (AnimationDrawable)

              imageView.getBackground();

           animationDrawable.start();

       }

    }

}

我在測試中發現兩點問題:

  1. 要在代碼中調用Imageview的setBackgroundResource方法,如果直接在XML佈局文件中設置其src屬性當觸發動畫時會FC。
  2. 在動畫start()之前要先stop(),不然在第一次動畫之後會停在最後一幀,這樣動畫就只會觸發一次。
  3. 最後一點是SDK中提到的,不要在onCreate中調用start,因爲AnimationDrawable還沒有完全跟Window相關聯,如果想要界面顯示時就開始動畫的話,可以在onWindowFoucsChanged()中調用start()。

 

   LayoutAnimationsController

1、什麼是LayoutAnimationsController

LayoutAnimationsController可以用於實現使多個控件按順序一個一個的顯示。

1)LayoutAnimationsController用於爲一個layout裏面的控件,或者是一個ViewGroup裏面的控件設置統一的動畫效果。

2)每一個控件都有相同的動畫效果

3)控件的動畫效果可以在不同的時間顯示出來

4)LayoutAnimationsController可以在xml文件當中設置,以可以在代碼當中進行設置。

2、在xml當中使用LayoutAnimationController

1)res/anim文件夾下創建一個名爲list_anim_layout.xml文件:

android:delay - 動畫間隔時間;子類動畫時間間隔 (延遲)   70% 也可以是一個浮點數 如“1.2”等

android:animationOrder - 動畫執行的循序(normal:順序,random:隨機,reverse:反向顯示)

android:animation – 引用動畫效果文件

<layoutAnimation

    xmlns:android="http://schemas.android.com/apk/res/android"

    android:delay="0.5"

    android:animationOrder="normal"

    android:animation="@anim/list_anim"/>

2)創建list_anim.xml文件,設置動畫效果

<?xml version="1.0" encoding="utf-8"?>

<set xmlns:android="http://schemas.android.com/apk/res/android"

    android:interpolator="@android:anim/accelerate_interpolator"

    android:shareInterpolator="true">

    <alpha

       android:fromAlpha="0.0"

       android:toAlpha="1.0"

       android:duration="1000"/>

</set>

 

3在佈局文件main.xml當中爲ListVIew添加如下配置

<ListView

       android:id="@id/android:list"

        android:layout_width="fill_parent"

        android:layout_height="wrap_content"

        android:scrollbars="vertical"

        android:layoutAnimation="@anim/list_anim_layout"/>

4)程序結構

 

 

 

5)list_anim_layout.xml

<layoutAnimation

    xmlns:android="http://schemas.android.com/apk/res/android"

    android:delay="0.5"

    android:animationOrder="normal"

    android:animation="@anim/list_anim"/>

6)list_anim.xml

<?xml version="1.0" encoding="utf-8"?>

<set xmlns:android="http://schemas.android.com/apk/res/android"

    android:interpolator="@android:anim/accelerate_interpolator"

    android:shareInterpolator="true">

    <alpha

       android:fromAlpha="0.0"

       android:toAlpha="1.0"

       android:duration="1000"/>

</set>

 

7)main.xml

<?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

    android:orientation="vertical"

    android:layout_width="fill_parent"

    android:layout_height="fill_parent"

    >

    <ListView

       android:id="@id/android:list"

        android:layout_width="fill_parent"

        android:layout_height="wrap_content"

        android:scrollbars="vertical"

        android:layoutAnimation="@anim/list_anim_layout"/>

    <Button

        android:id="@+id/button"

        android:layout_width="fill_parent"

        android:layout_height="wrap_content"

        android:text="測試"/>

</LinearLayout>

8)item.xml

<?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

    android:layout_width="fill_parent"

    android:layout_height="fill_parent"

    android:orientation="horizontal"

    android:paddingLeft="10dip"

    android:paddingRight="10dip"

    android:paddingTop="1dip"

    android:paddingBottom="1dip">

    <TextView android:id="@+id/name"

       android:layout_width="180dip"

       android:layout_height="30dip"

       android:textSize="5pt"

       android:singleLine="true" />

    <TextView android:id="@+id/sex"

       android:layout_width="fill_parent"

       android:layout_height="fill_parent"

       android:textSize="5pt"

       android:singleLine="true"/>

</LinearLayout>

9)java文件

public class Animation2Activity extendsListActivity {

    private Button button = null;

    private ListView listView = null;

    @Override

    public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.main);

        listView = getListView();

        button = (Button)findViewById(R.id.button);

        button.setOnClickListener(newButtonListener());

    }

    private ListAdapter createListAdapter() {

       List<HashMap<String,String>> list =

           new ArrayList<HashMap<String,String>>();

       HashMap<String,String> m1 = new HashMap<String,String>();

       m1.put("name", "bauble");

       m1.put("sex", "male");

       HashMap<String,String> m2 = new HashMap<String,String>();

       m2.put("name", "Allorry");

       m2.put("sex", "male");

       HashMap<String,String> m3 = new HashMap<String,String>();

       m3.put("name", "Allotory");

       m3.put("sex", "male");

       HashMap<String,String> m4 = new HashMap<String,String>();

       m4.put("name", "boolbe");

       m4.put("sex", "male");

       list.add(m1);

       list.add(m2);

       list.add(m3);

       list.add(m4);

       SimpleAdapter simpleAdapter = new SimpleAdapter(

              this,list,R.layout.item,new String[]{"name","sex"},

              new int[]{R.id.name,R.id.sex});

       return simpleAdapter;

    }

    private class ButtonListener implementsOnClickListener{

       public void onClick(View v) {

           listView.setAdapter(createListAdapter());

       }

    }

}

 

備註:要將整個動畫效果設置到LinerLayout中,可以這樣設置:

<LinearLayoutxmlns:android="http://schemas.android.com/apk/res/android"

    android:orientation="vertical"

    android:layout_width="fill_parent"

    android:layout_height="fill_parent"

    android:layoutAnimation="@anim/list_anim_layout"

 

3、在代碼當中使用LayoutAnimationController

1)去掉main.xml中的android:layoutAnimation="@anim/list_anim_layout"/>

2)創建一個Animation對象:可以通過裝載xml文件,或者是直接使用Animation的構造方法創建Animation對象;

Animation animation = (Animation) AnimationUtils.loadAnimation(

                  Animation2Activity.this, R.anim.list_anim);

3)創建LayoutAnimationController對象:  

LayoutAnimationController controller = new LayoutAnimationController(animation); 

            

4)設置控件的顯示順序以及延遲時間

controller.setOrder(LayoutAnimationController.ORDER_NORMAL); 

controller.setDelay(0.5f);        

5)爲ListView設置LayoutAnimationController屬性:

listView.setLayoutAnimation(controller);

完整代碼:

private class ButtonListener implementsOnClickListener {

       public void onClick(View v) {

           listView.setAdapter(createListAdapter());

           Animation animation = (Animation) AnimationUtils.loadAnimation(

                  Animation2Activity.this, R.anim.list_anim);

          

           LayoutAnimationController controller = new LayoutAnimationController(animation); 

           controller.setOrder(LayoutAnimationController.ORDER_NORMAL); 

           controller.setDelay(0.5f);

           listView.setLayoutAnimation(controller); 

       }

    }

 

 AnimationListener

1、什麼是AnimationListener

1).AnimationListener是一個監聽器,該監聽器在動畫執行的各個階段會得到通知,從而調用相應的方法;

2).AnimationListener主要包括如下三個方法:

n         ·onAnimationEnd(Animation animation) - 當動畫結束時調用

n         ·onAnimationRepeat(Animation animation) - 當動畫重複時調用

n         ·onAniamtionStart(Animation animation) - 當動畫啓動時調用

2、具體實現

1main.xml

<?xml version="1.0" encoding="utf-8"?>

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"

    android:id="@+id/layout"

    android:orientation="vertical"

    android:layout_width="fill_parent"

    android:layout_height="fill_parent">

    <Button android:id="@+id/addButton"

       android:layout_width="fill_parent"

       android:layout_height="wrap_content"

       android:layout_alignParentBottom="true"

       android:text="添加圖片" />

    <Button android:id="@+id/deleteButton"

       android:layout_width="fill_parent"

       android:layout_height="wrap_content"

       android:layout_above="@id/addButton"

       android:text="刪除圖片" />

    <ImageView android:id="@+id/image"

       android:layout_width="wrap_content"

       android:layout_height="wrap_content"

       android:layout_centerInParent="true"

       android:layout_marginTop="100dip"

       android:src="@drawable/an" />

</RelativeLayout>

2).java文件

public class Animation2Activity extends Activity {

    private Button addButton = null;

    private Button deleteButton = null;

    private ImageView imageView = null;

    private ViewGroup viewGroup = null;

    @Override

    public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.main);

        addButton = (Button)findViewById(R.id.addButton);

        deleteButton = (Button)findViewById(R.id.deleteButton);

        imageView = (ImageView)findViewById(R.id.image);

        //LinearLayout下的一組控件

        viewGroup = (ViewGroup)findViewById(R.id.layout);

        addButton.setOnClickListener(newAddButtonListener());

        deleteButton.setOnClickListener(newDeleteButtonListener());

    }

    private class AddButtonListener implements OnClickListener{

       public void onClick(View v) {

           //淡入

           AlphaAnimation animation = new AlphaAnimation(0.0f, 1.0f);

           animation.setDuration(1000);

           animation.setStartOffset(500);

           //創建一個新的ImageView

           ImageView newImageView = new ImageView(

              Animation2Activity.this);

           newImageView.setImageResource(R.drawable.an);

           viewGroup.addView(newImageView,

              new LayoutParams(

                  LayoutParams.FILL_PARENT,

                  LayoutParams.WRAP_CONTENT));

           newImageView.startAnimation(animation);

       }

    }

    private class DeleteButtonListener implements OnClickListener{

       public void onClick(View v) {

           //淡出

           AlphaAnimation animation = new AlphaAnimation(1.0f, 0.0f);

           animation.setDuration(1000);

           animation.setStartOffset(500);

           //Aniamtion對象設置監聽器

           animation.setAnimationListener(

              new RemoveAnimationListener());

           imageView.startAnimation(animation);

       }

    }

    private class RemoveAnimationListener implements AnimationListener{

       //動畫效果執行完時remove

       public void onAnimationEnd(Animation animation) {

           System.out.println("onAnimationEnd");

           viewGroup.removeView(imageView);

       }

       public void onAnimationRepeat(Animation animation) {

           System.out.println("onAnimationRepeat");

       }

       public void onAnimationStart(Animation animation) {

           System.out.println("onAnimationStart");

       }

    }

}

3、總結一下

可以在Activity中動態添加和刪除控件,方法是:

1)取到那個Layout

viewGroup = (ViewGroup)findViewById(R.id.layout);

2)添加時,先創建對象,然後添加

ImageView newImageView = new ImageView(

              Animation2Activity.this);

newImageView.setImageResource(R.drawable.an);

viewGroup.addView(newImageView,

              new LayoutParams(

                  LayoutParams.FILL_PARENT,

                  LayoutParams.WRAP_CONTENT));

3)刪除時,直接刪除。

viewGroup.removeView(imageView);

 Property Animation

屬性動畫,這個是在Android 3.0中才引進的,以前學WPF時裏面的動畫機制好像就是這個,它更改的是對象的實際屬性,在View Animation(Tween Animation)中,其改變的是View的繪製效果,真正的View的屬性保持不變,比如無論你在對話中如何縮放Button的大小,Button的有效點擊區域還是沒有應用動畫時的區域,其位置與大小都不變。而在Property Animation中,改變的是對象的實際屬性,如Button的縮放,Button的位置與大小屬性值都改變了。而且Property Animation不止可以應用於View,還可以應用於任何對象。Property Animation只是表示一個值在一段時間內的改變,當值改變時要做什麼事情完全是你自己決定的。

在Property Animation中,可以對動畫應用以下屬性:

  • Duration:動畫的持續時間
  • TimeInterpolation:屬性值的計算方式,如先快後慢
  • TypeEvaluator:根據屬性的開始、結束值與TimeInterpolation計算出的因子計算出當前時間的屬性值
  • Repeat Count and behavoir:重複次數與方式,如播放3次、5次、無限循環,可以此動畫一直重複,或播放完時再反向播放
  • Animation sets:動畫集合,即可以同時對一個對象應用幾個動畫,這些動畫可以同時播放也可以對不同動畫設置不同開始偏移
  • Frame refreash delay:多少時間刷新一次,即每隔多少時間計算一次屬性值,默認爲10ms,最終刷新時間還受系統進程調度與硬件的影響

1 Property Animation的工作方式

對於下圖的動畫,這個對象的X座標在40ms內從0移動到40 pixel.按默認的10ms刷新一次,這個對象會移動4次,每次移動40/4=10pixel。

也可以改變屬性值的改變方法,即設置不同的interpolation,在下圖中運動速度先逐漸增大再逐漸減小

下圖顯示了與上述動畫相關的關鍵對象

ValueAnimator  表示一個動畫,包含動畫的開始值,結束值,持續時間等屬性。

ValueAnimator封裝了一個TimeInterpolator,TimeInterpolator定義了屬性值在開始值與結束值之間的插值方法。

ValueAnimator還封裝了一個TypeAnimator,根據開始、結束值與TimeIniterpolator計算得到的值計算出屬性值。

ValueAnimator根據動畫已進行的時間跟動畫總時間(duration)的比計算出一個時間因子(0~1),然後根據TimeInterpolator計算出另一個因子,最後TypeAnimator通過這個因子計算出屬性值,如上例中10ms時:

首先計算出時間因子,即經過的時間百分比:t=10ms/40ms=0.25

經插值計算(inteplator)後的插值因子:大約爲0.15,上述例子中用了AccelerateDecelerateInterpolator,計算公式爲(input即爲時間因子):

(Math.cos((input + 1) * Math.PI) / 2.0f) + 0.5f;  

最後根據TypeEvaluator計算出在10ms時的屬性值:0.15*(40-0)=6pixel。上例中TypeEvaluator爲FloatEvaluator,計算方法爲 :

public Float evaluate(float fraction, Number startValue, Number endValue) {
    float startFloat = startValue.floatValue();
    return startFloat + fraction * (endValue.floatValue() - startFloat);
}

參數分別爲上一步的插值因子,開始值與結束值。

2 ValueAnimator

ValueAnimator包含Property Animation動畫的所有核心功能,如動畫時間,開始、結束屬性值,相應時間屬性值計算方法等。應用Property Animation有兩個步聚:

  1. 計算屬性值
  2. 根據屬性值執行相應的動作,如改變對象的某一屬性。

ValuAnimiator只完成了第一步工作,如果要完成第二步,需要實現ValueAnimator.onUpdateListener接口,這個接口只有一個函數onAnimationUpdate(),在這個函數中會傳入ValueAnimator對象做爲參數,通過這個ValueAnimator對象的getAnimatedValue()函數可以得到當前的屬性值如:

複製代碼
ValueAnimator animation = ValueAnimator.ofFloat(0f, 1f);
animation.setDuration(1000);
animation.addUpdateListener(new AnimatorUpdateListener() {
@Override
public void onAnimationUpdate(ValueAnimator animation) {
Log.i("update", ((Float) animation.getAnimatedValue()).toString());
}
});
animation.setInterpolator(new CycleInterpolator(3));
animation.start();
複製代碼

此示例中只是向Logcat輸出了一些信息,可以改爲想做的工作。

Animator.AnimatorListener

複製代碼
onAnimationStart()

onAnimationEnd()

onAnimationRepeat()

//當動畫被取消時調用,同時會調用onAnimationEnd().
onAnimationCancel()
複製代碼

ValueAnimator.AnimatorUpdateListener

onAnimationUpdate()  //通過監聽這個事件在屬性的值更新時執行相應的操作,對於ValueAnimator一般要監聽此事件執行相應的動作,不然Animation沒意義,在ObjectAnimator(繼承自ValueAnimator)中會自動更新屬性,如無必要不必監聽。在函數中會傳遞一個ValueAnimator參數,通過此參數的getAnimatedValue()取得當前動畫屬性值。

可以繼承AnimatorListenerAdapter而不是實現AnimatorListener接口來簡化操作,這個類對AnimatorListener中的函數都定義了一個空函數體,這樣我們就只用定義想監聽的事件而不用實現每個函數卻只定義一空函數體。

複製代碼
ObjectAnimator oa=ObjectAnimator.ofFloat(tv, "alpha", 0f, 1f);
oa.setDuration(3000);
oa.addListener(new AnimatorListenerAdapter(){
    public void on AnimationEnd(Animator animation){
        Log.i("Animation","end");
    }
});
oa.start();
複製代碼

3 ObjectAnimator

繼承自ValueAnimator,要指定一個對象及該對象的一個屬性,當屬性值計算完成時自動設置爲該對象的相應屬性,即完成了Property Animation的全部兩步操作。實際應用中一般都會用ObjectAnimator來改變某一對象的某一屬性,但用ObjectAnimator有一定的限制,要想使用ObjectAnimator,應該滿足以下條件:

  • 對象應該有一個setter函數:set<PropertyName>(駝峯命名法)
  • 如上面的例子中,像ofFloat之類的工場方法,第一個參數爲對象名,第二個爲屬性名,後面的參數爲可變參數,如果values…參數只設置了一個值的話,那麼會假定爲目的值,屬性值的變化範圍爲當前值到目的值,爲了獲得當前值,該對象要有相應屬性的getter方法:get<PropertyName>
  • 如果有getter方法,其應返回值類型應與相應的setter方法的參數類型一致。

如果上述條件不滿足,則不能用ObjectAnimator,應用ValueAnimator代替。

複製代碼
tv=(TextView)findViewById(R.id.textview1);
btn=(Button)findViewById(R.id.button1);
btn.setOnClickListener(new OnClickListener() {
  @Override
  public void onClick(View v) {
    ObjectAnimator oa=ObjectAnimator.ofFloat(tv, "alpha", 0f, 1f);
    oa.setDuration(3000);
    oa.start();
  }
});
複製代碼

把一個TextView的透明度在3秒內從0變至1。

根據應用動畫的對象或屬性的不同,可能需要在onAnimationUpdate函數中調用invalidate()函數刷新視圖。

4 通過AnimationSet應用多個動畫

AnimationSet提供了一個把多個動畫組合成一個組合的機制,並可設置組中動畫的時序關係,如同時播放,順序播放等。

以下例子同時應用5個動畫:

  1. 播放anim1;
  2. 同時播放anim2,anim3,anim4;
  3. 播放anim5。
AnimatorSet bouncer = new AnimatorSet();
bouncer.play(anim1).before(anim2);
bouncer.play(anim2).with(anim3);
bouncer.play(anim2).with(anim4)
bouncer.play(anim5).after(amin2);
animatorSet.start();

5 TypeEvalutors

根據屬性的開始、結束值與TimeInterpolation計算出的因子計算出當前時間的屬性值,android提供了以下幾個evalutor:

  • IntEvaluator:屬性的值類型爲int;
  • FloatEvaluator:屬性的值類型爲float;
  • ArgbEvaluator:屬性的值類型爲十六進制顏色值;
  • TypeEvaluator:一個接口,可以通過實現該接口自定義Evaluator。

自定義TypeEvalutor很簡單,只需要實現一個方法,如FloatEvalutor的定義:

複製代碼
public class FloatEvaluator implements TypeEvaluator {
    public Object evaluate(float fraction, Object startValue, Object endValue) {
        float startFloat = ((Number) startValue).floatValue();
        return startFloat + fraction * (((Number) endValue).floatValue() - startFloat);
    }
}
複製代碼

根據動畫執行的時間跟應用的Interplator,會計算出一個0~1之間的因子,即evalute函數中的fraction參數,通過上述FloatEvaluator應該很好看出其意思。

6 TimeInterplator

Time interplator定義了屬性值變化的方式,如線性均勻改變,開始慢然後逐漸快等。在Property Animation中是TimeInterplator,在View Animation中是Interplator,這兩個是一樣的,在3.0之前只有Interplator,3.0之後實現代碼轉移至了TimeInterplator。Interplator繼承自TimeInterplator,內部沒有任何其他代碼。

  • AccelerateInterpolator          加速,開始時慢中間加速
  • DecelerateInterpolator         減速,開始時快然後減速
  • AccelerateDecelerateInterolator    先加速後減速,開始結束時慢,中間加速
  • AnticipateInterpolator        反向 ,先向相反方向改變一段再加速播放
  • AnticipateOvershootInterpolator    反向加回彈,先向相反方向改變,再加速播放,會超出目的值然後緩慢移動至目的值
  • BounceInterpolator         跳躍,快到目的值時值會跳躍,如目的值100,後面的值可能依次爲85,77,70,80,90,100
  • CycleIinterpolator         循環,動畫循環一定次數,值的改變爲一正弦函數:Math.sin(2 * mCycles * Math.PI * input)
  • LinearInterpolator         線性,線性均勻改變
  • OvershottInterpolator        回彈,最後超出目的值然後緩慢改變到目的值
  • TimeInterpolator           一個接口,允許你自定義interpolator,以上幾個都是實現了這個接口

7 當Layout改變時應用動畫

ViewGroup中的子元素可以通過setVisibility使其Visible、Invisible或Gone,當有子元素可見性改變時(VISIBLE、GONE),可以向其應用動畫,通過LayoutTransition類應用此類動畫:

transition.setAnimator(LayoutTransition.DISAPPEARING, customDisappearingAnim);

通過setAnimator應用動畫,第一個參數表示應用的情境,可以以下4種類型:

  • APPEARING        當一個元素在其父元素中變爲Visible時對這個元素應用動畫
  • CHANGE_APPEARING    當一個元素在其父元素中變爲Visible時,因系統要重新佈局有一些元素需要移動,對這些要移動的元素應用動畫
  • DISAPPEARING       當一個元素在其父元素中變爲GONE時對其應用動畫
  • CHANGE_DISAPPEARING   當一個元素在其父元素中變爲GONE時,因系統要重新佈局有一些元素需要移動,這些要移動的元素應用動畫.

第二個參數爲一Animator。

mTransitioner.setStagger(LayoutTransition.CHANGE_APPEARING, 30);

此函數設置動畫延遲時間,參數分別爲類型與時間。

8 Keyframes

keyFrame是一個 時間/值 對,通過它可以定義一個在特定時間的特定狀態,即關鍵幀,而且在兩個keyFrame之間可以定義不同的Interpolator,就好像多個動畫的拼接,第一個動畫的結束點是第二個動畫的開始點。KeyFrame是抽象類,要通過ofInt(),ofFloat(),ofObject()獲得適當的KeyFrame,然後通過PropertyValuesHolder.ofKeyframe獲得PropertyValuesHolder對象,如以下例子:

複製代碼
Keyframe kf0 = Keyframe.ofInt(0, 400);
Keyframe kf1 = Keyframe.ofInt(0.25f, 200);
Keyframe kf2 = Keyframe.ofInt(0.5f, 400);
Keyframe kf4 = Keyframe.ofInt(0.75f, 100);
Keyframe kf3 = Keyframe.ofInt(1f, 500);
PropertyValuesHolder pvhRotation = PropertyValuesHolder.ofKeyframe("width", kf0, kf1, kf2, kf4, kf3);
ObjectAnimator rotationAnim = ObjectAnimator.ofPropertyValuesHolder(btn2, pvhRotation);
rotationAnim.setDuration(2000);
複製代碼

上述代碼的意思爲:設置btn對象的width屬性值使其:

  • 開始時 Width=400
  • 動畫開始1/4時 Width=200
  • 動畫開始1/2時 Width=400
  • 動畫開始3/4時 Width=100
  • 動畫結束時 Width=500
第一個參數爲時間百分比,第二個參數是在第一個參數的時間時的屬性值。
定義了一些Keyframe後,通過PropertyValuesHolder類的方法ofKeyframe一個PropertyValuesHolder對象,然後通過ObjectAnimator.ofPropertyValuesHolder獲得一個Animator對象。
用下面的代碼可以實現同樣的效果(上述代碼時間值是線性,變化均勻):
ObjectAnimator oa=ObjectAnimator.ofInt(btn2, "width", 400,200,400,100,500);
oa.setDuration(2000);
oa.start();

9 Animating Views

在View Animation中,對View應用Animation並沒有改變View的屬性,動畫的實現是通過其Parent View實現的,在View被drawn時Parents View改變它的繪製參數,draw後再改變參數invalidate,這樣雖然View的大小或旋轉角度等改變了,但View的實際屬性沒變,所以有效區域還是應用動畫之前的區域,比如你把一按鈕放大兩倍,但還是放大這前的區域可以觸發點擊事件。爲了改變這一點,在Android 3.0中給View增加了一些參數並對這些參數增加了相應的getter/setter函數(ObjectAnimator要用這些函數改變這些屬性):

  • translationX,translationY: View相對於原始位置的偏移量
  • rotation,rotationX,rotationY: 旋轉,rotation用於2D旋轉角度,3D中用到後兩個
  • scaleX,scaleY: 縮放比
  • x,y: View的最終座標,是View的left,top位置加上translationX,translationY
  • alpha: 透明度
跟位置有關的參數有3個,以X座標爲例,可以通過getLeft(),getX(),getTranslateX()獲得,若有一Button btn2,佈局時其座標爲(40,0):
複製代碼
//應用動畫之前
btn2.getLeft(); //40
btn2.getX(); //40
btn2.getTranslationX(); //0
//應用translationX動畫
ObjectAnimator oa=ObjectAnimator.ofFloat(btn2,"translationX", 200);
oa.setDuration(2000);
oa.start();
/*應用translationX動畫後
btn2.getLeft(); //40
btn2.getX(); //240
btn2.getTranslationX(); //200
*/
//應用X動畫,假設沒有應用之前的translationX動畫
ObjectAnimator oa=ObjectAnimator.ofFloat(btn2, "x", 200);
oa.setDuration(2000);
oa.start();
/*應用X動畫後
btn2.getLeft(); //40
btn2.getX(); //200
btn2.getTranslationX(); //160
*/
複製代碼
無論怎樣應用動畫,原來的佈局時的位置通過getLeft()獲得,保持不變;
  X是View最終的位置;
  translationX爲最終位置與佈局時初始位置這差。
  所以若就用translationX即爲在原來基礎上移動多少,X爲最終多少
  getX()的值爲getLeft()與getTranslationX()的和
  對於X動畫,源代碼是這樣的:
case X:
info.mTranslationX = value - mView.mLeft;
break;

Property Animation也可以在XML中定義

  • <set> - AnimatorSet
  • <animator> - ValueAnimator
  • <objectAnimator> - ObjectAnimator
XML文件應放大/res/animator/中,通過以下方式應用動畫:
AnimatorSet set = (AnimatorSet) AnimatorInflater.loadAnimator(myContext, R.anim.property_animator);
set.setTarget(myObject);
set.start();

10 ViewPropertyAnimator


如果需要對一個View的多個屬性進行動畫可以用ViewPropertyAnimator類,該類對多屬性動畫進行了優化,會合並一些invalidate()來減少刷新視圖,該類在3.1中引入。

以下兩段代碼實現同樣的效果: 

PropertyValuesHolder pvhX = PropertyValuesHolder.ofFloat("x", 50f);
PropertyValuesHolder pvhY = PropertyValuesHolder.ofFloat("y", 100f);
ObjectAnimator.ofPropertyValuesHolder(myView, pvhX, pvyY).start();
myView.animate().x(50f).y(100f);


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章