Android Animation初步

Animation從整體來講能夠分爲兩類:
java

  1. Tweened Animations:該類提供了旋轉,移動,伸展,淡入淡出等效果android

  2. Frame-By-Frame Animations:該類能夠建立一個Drawable序列,這些Drawable能夠按照指定的事件間隔一個一個顯示,和動畫片差很少app

1、Tweened Animations

Tweened Animations也有四種類型:ide

  1. Alpha:淡入淡出效果測試

  2. Scale:縮放效果動畫

  3. Rotate:旋轉效果ui

  4. Translate:移動效果this

設置動畫效果能夠在XML文件中設置,也能夠在Java代碼中設置。咱們先來說解在Java代碼中怎麼設置這四種動畫效果spa

Java代碼中設置動畫效果的步驟:.net

  1. 建立一個AnimationSet對象(AnimationSet是存放多個Animations的集合)

  2. 根據須要建立相應的Animation對象

  3. 根據須要對Animation對象的各個屬性進行設值

  4. 將Animation對象添加到AnimationSet對象中

  5. 使用控件的startAnimation()方法執行AnimationSet

Java代碼中的通用屬性:

  • setDuration(long durationMillis):設置動畫持續事件(單位:毫秒)

  • setFillAfter(boolean fillAfter):若是fillAfter設爲true,則動畫執行後,控件將停留在動畫結束的狀態

  • setFillBefore(boolean fillBefore):若是fillBefore設爲true,則動畫執行後,控件將回到動畫開始的狀態

  • setStartOffset(long startOffset):設置動畫執行以前等待的時間(單位:毫秒)

  • setRepeatCount(int repeatCount):設置動畫重複的次數

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

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

setInterpolator(new AccelerateInterpolator()):加速

setInterpolator(new DecelerateInterpolator()):減速

setInterpolator(new CycleInterpolator()):動畫循環播放特定次數,速率改變沿着正弦曲線

setInterpolator(new LinearInterpolator()):勻速

以及其餘一些特定的動畫效果

Java代碼中設置動畫效果的Demo(AnimationDemo01):

main.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" >
    <ImageView
        android:id="@+id/p_w_picpathView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="100dip"
        android:src="@drawable/ic_launcher" />
    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:gravity="bottom"
        android:orientation="vertical" >
        <Button
            android:id="@+id/alphaButton"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:text="測試alpha動畫效果" />
        <Button
            android:id="@+id/scaleButton"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:text="測試scale動畫效果" />
        <Button
            android:id="@+id/rotateButton"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:text="測試rotate動畫效果" />
        <Button
            android:id="@+id/translateButton"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:text="測試translate動畫效果" />
    </LinearLayout>
</LinearLayout>
AnimationDemoActivity.java
package com.tianjf;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.AnimationSet;
import android.view.animation.RotateAnimation;
import android.view.animation.ScaleAnimation;
import android.view.animation.TranslateAnimation;
import android.widget.Button;
import android.widget.ImageView;
public class AnimationDemoActivity extends Activity implements OnClickListener {
    private ImageView mImageView;
    private Button mAlphaButton;
    private Button mScaleButton;
    private Button mRotateButton;
    private Button mTranslateButton;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        mImageView = (ImageView) findViewById(R.id.p_w_picpathView);
        mAlphaButton = (Button) findViewById(R.id.alphaButton);
        mScaleButton = (Button) findViewById(R.id.scaleButton);
        mRotateButton = (Button) findViewById(R.id.rotateButton);
        mTranslateButton = (Button) findViewById(R.id.translateButton);
        mAlphaButton.setOnClickListener(this);
        mScaleButton.setOnClickListener(this);
        mRotateButton.setOnClickListener(this);
        mTranslateButton.setOnClickListener(this);
    }
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
        case R.id.alphaButton:
            // 建立一個AnimationSet對象(AnimationSet是存放多個Animations的集合)
            AnimationSet animationSet = new AnimationSet(true);
            // 建立一個AlphaAnimation對象(參數表示從徹底不透明到徹底透明)
            AlphaAnimation alphaAnimation = new AlphaAnimation(1, 0);
            // 設置動畫執行的時間(單位:毫秒)
            alphaAnimation.setDuration(1000);
            // 將AlphaAnimation對象添加到AnimationSet當中
            animationSet.addAnimation(alphaAnimation);
            // 使用ImageView的startAnimation方法開始執行動畫
            mImageView.startAnimation(animationSet);
            break;
        case R.id.scaleButton:
            // 建立一個AnimationSet對象(AnimationSet是存放多個Animations的集合)
            animationSet = new AnimationSet(true);
            // 建立一個ScaleAnimation對象(以某個點爲中心縮放)
            ScaleAnimation scaleAnimation = new ScaleAnimation(1, 0.1f, 1, 0.1f,
                    Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
            // 設置動畫執行以前等待的時間(單位:毫秒)
            scaleAnimation.setStartOffset(1000);
            // 設置動畫執行的時間(單位:毫秒)
            scaleAnimation.setDuration(2000);
            // 若是fillAfter設爲true,則動畫執行後,控件將停留在動畫結束的狀態
            // 運行了一下發現如下奇怪的現象
            // scaleAnimation.setFillAfter(true);不會停留在動畫結束的狀態
            // animationSet.setFillAfter(true);則會停留在動畫結束的狀態
            animationSet.setFillAfter(true);
                        // 將ScaleAnimation對象添加到AnimationSet當中
                       &nbsp;animationSet.addAnimation(scaleAnimation);
                        // 使用ImageView的startAnimation方法開始執行動畫
&nbsp;                       mImageView.startAnimation(animationSet);
            break;
        case R.id.rotateButton:
            // 建立一個AnimationSet對象(AnimationSet是存放多個Animations的集合)
            animationSet = new AnimationSet(true);
            // 建立一個RotateAnimation對象(以某個點爲圓心旋轉360度)
            RotateAnimation rotateAnimation = new RotateAnimation(0, 360,
                    Animation.RELATIVE_TO_PARENT, 0.5f, Animation.RELATIVE_TO_PARENT, 0.25f);
            // 設置動畫執行的時間(單位:毫秒)
            rotateAnimation.setDuration(5000);
            // 將RotateAnimation對象添加到AnimationSet當中
            animationSet.addAnimation(rotateAnimation);
            // 使用ImageView的startAnimation方法開始執行動畫
            mImageView.startAnimation(animationSet);
            break;
        case R.id.translateButton:
            // 建立一個AnimationSet對象(AnimationSet是存放多個Animations的集合)
            animationSet = new AnimationSet(true);
            // 建立一個RotateAnimation對象(從某個點移動到另外一個點)
            TranslateAnimation translateAnimation = new TranslateAnimation(
                    Animation.RELATIVE_TO_SELF, 0f, Animation.RELATIVE_TO_SELF, 0.5f,
                    Animation.RELATIVE_TO_SELF, 0f, Animation.RELATIVE_TO_SELF, 1.0f);
            // 設置動畫執行的時間(單位:毫秒)
            translateAnimation.setDuration(1000);
            // 將TranslateAnimation對象添加到AnimationSet當中
            animationSet.addAnimation(translateAnimation);
            // 使用ImageView的startAnimation方法開始執行動畫
            mImageView.startAnimation(animationSet);
            break;
        default:
            break;
        }
    }
}
AlphaAnimation很簡單,很少說,直接看代碼註釋

剩下的3中動畫效果都涉及到了參考點的問題,下面咱們逐一解釋

RotateAnimation的建立中用到了Animation.RELATIVE_TO_PARENT(表示以父控件爲參考),另外還有2種參考:Animation.RELATIVE_TO_SELF(以自身爲參考),Animation.ABSOLUTE(絕對座標,沒有參考)

咱們就拿Animation.RELATIVE_TO_PARENT來畫圖講解到底RotateAnimation旋轉的圓心在哪兒?

例子中,X軸設置了相對於父控件,值是0.5f;Y軸設置了相對於父控件,值是0.25f。也就是說,圓心是0.5個父控件的width和0.25個父控件的height

那麼,控件就圍繞着上圖的圓心,從0°旋轉到360°(若是是0,-360,那麼就是0°旋轉到-360°)

以父控件爲參照理解了的話,以自身爲參考就能夠觸類旁通了。

ScaleAnimation的建立的參數的解釋:縮放的中心點能夠按照上文中的計算方法,縮小後的圖片大小是0.1個自身width,0.1個自身height,至關於縮小90%

TranslateAnimation的建立的參數的解釋:參數主要是決定移動的起始點和終了點,計算方法參考上文

上面的Java代碼設置動畫效果有一個缺點:代碼的可複用性很低,不利於維護。爲了維護,能夠使用XML來設置動畫效果

XML中設置動畫效果的步驟:

  1. 在res文件夾下新建一個名爲anim的文件夾

  2. 建立xml文件,並首先加入set標籤(set標籤就至關於Java代碼中的AnimationSet)

  3. 在Set標籤中加入alpha,scale,rotate,translate標籤(至關於Java代碼中的AlphaAnimation,ScaleAnimation,RotateAnimation,TranslateAnimation)

  4. 在Java代碼中使用AnimationUtils的loadAnimation方法來加載XML文件,並獲得一個Animation對象

  5. 使用控件的startAnimation()方法執行這個Animation對象

XML中的通用屬性:

  • android:duration:設置動畫持續事件(單位:毫秒)

  • android:fillAfter:若是fillAfter設爲true,則動畫執行後,控件將停留在動畫結束的狀態

  • android:fillBefore:若是fillBefore設爲true,則動畫執行後,控件將回到動畫開始的狀態

  • android:startOffset(long startOffset):設置動畫執行以前等待的時間(單位:毫秒)

  • android:repeatCount(int repeatCount):設置動畫重複的次數

  • android:interpolator:設置動畫的變化速度

android:interpolator="@android:anim/accelerate_decelerate_interpolator":先加速,後減速

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

android:interpolator="@android:anim/decelerate_interpolator":減速

android:interpolator="@android:anim/cycle_Interpolator":動畫循環播放特定次數,速率改變沿着正弦曲線

android:interpolator="@android:anim/linear_Interpolator":勻速

以及其餘一些特定的動畫效果

XML中設置動畫效果的Demo(AnimationDemo02):


main.xml

同上

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" >
    <alpha
        android:duration="500"
        android:fromAlpha="1.0"
        android:startOffset="500"
        android:toAlpha="0.0" />
</set>
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" >
    <rotate
        android:duration="5000"
        android:fromDegrees="0"
        android:pivotX="50%"
        android:pivotY="50%"
        android:toDegrees="360" />
</set>
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" >
    <scale
        android:duration="2000"
        android:fromXScale="1.0"
        android:fromYScale="1.0"
        android:pivotX="50%"
        android:pivotY="50%"
        android:toXScale="0.0"
        android:toYScale="0.0" />
</set>
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" >
    <translate
        android:duration="2000"
        android:fromXDelta="50%"
        android:fromYDelta="0%"
        android:toXDelta="100%"
        android:toYDelta="100%" />
</set>
AnimationDemoActivity.java
package com.tianjf;
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;
import android.widget.ImageView;
public class AnimationDemoActivity extends Activity implements OnClickListener {
    private ImageView mImageView;
    private Button mAlphaButton;
    private Button mScaleButton;
    private Button mRotateButton;
    private Button mTranslateButton;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        mImageView = (ImageView) findViewById(R.id.p_w_picpathView);
        mAlphaButton = (Button) findViewById(R.id.alphaButton);
        mScaleButton = (Button) findViewById(R.id.scaleButton);
        mRotateButton = (Button) findViewById(R.id.rotateButton);
        mTranslateButton = (Button) findViewById(R.id.translateButton);
        mAlphaButton.setOnClickListener(this);
        mScaleButton.setOnClickListener(this);
        mRotateButton.setOnClickListener(this);
        mTranslateButton.setOnClickListener(this);
    }
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
        case R.id.alphaButton:
            Animation alphaAnimation = AnimationUtils.loadAnimation(this, R.anim.alpha);
            mImageView.startAnimation(alphaAnimation);
            break;
        case R.id.scaleButton:
            Animation scaleAnimation = AnimationUtils.loadAnimation(this, R.anim.scale);
            mImageView.startAnimation(scaleAnimation);
            break;
        case R.id.rotateButton:
            Animation rotateAnimation = AnimationUtils.loadAnimation(this, R.anim.rotate);
            mImageView.startAnimation(rotateAnimation);
            break;
        case R.id.translateButton:
            Animation translateAnimation = AnimationUtils.loadAnimation(this, R.anim.translate);
            mImageView.startAnimation(translateAnimation);
            break;
        default:
            break;
        }
    }
}
關於屬性的講解,已經在AnimationDemo01中講解過了,在此就再也不重複了。


值得一提的是,AnimationDemo01中出現的絕對定位(Animation.ABSOLUTE),相對於自身定位(Animation.RELATIVE_TO_SELF),相對於父控件定位(Animation.RELATIVE_TO_PAREN),在XML文件中用XX(絕對),XX%(相對於自身),XX%p(相對於父控件)


上面兩個例子都有一個類叫:AnimationSet(XML文件中是set標籤),這個AnimationSet就至關於一個集合,能夠存放一個或多個Animation對象,若是咱們對AnimationSet設置屬性值,那麼,這些屬性值將應用到AnimationSet下的全部Animation對象中去。



2、Frame-By-Frame Animations


直接上代碼(AnimationDemo03)

main.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" >
    <ImageView
        android:id="@+id/p_w_picpathView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="100dip" />
    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:gravity="bottom"
        android:orientation="vertical" >
        <Button
            android:id="@+id/frameByFrameButton"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:text="測試Frame-By-Frame動畫效果" />
    </LinearLayout>
</LinearLayout>
anim_nv.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/nv1"
        android:duration="500"/>
    <item
        android:drawable="@drawable/nv2"
        android:duration="500"/>
    <item
        android:drawable="@drawable/nv3"
        android:duration="500"/>
    <item
        android:drawable="@drawable/nv4"
        android:duration="500"/>
</animation-list>
AnimationDemoActivity.java
package com.tianjf;
import android.app.Activity;
import android.graphics.drawable.AnimationDrawable;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
public class AnimationDemoActivity extends Activity implements OnClickListener {
    private ImageView mImageView;
    private Button mFrameByFrameButton;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        mImageView = (ImageView) findViewById(R.id.p_w_picpathView);
        mFrameByFrameButton = (Button) findViewById(R.id.frameByFrameButton);
        mFrameByFrameButton.setOnClickListener(this);
    }
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
        case R.id.frameByFrameButton:
            // 爲ImageView設置背景資源
            mImageView.setBackgroundResource(R.drawable.anim_nv);
            // 經過ImageView獲得AnimationDrawable
            AnimationDrawable animationDrawable = (AnimationDrawable) mImageView.getBackground();
            // 開始執行動畫
            animationDrawable.start();
            break;
        default:
            break;
        }
    }
}


3、LayoutAnimationController

什麼是LayoutAnimationController呢?LayoutAnimationController用於爲一個Layout裏面的一組控件設置相同的動畫效果,並能夠控制這一組動畫在不一樣的時間出現


LayoutAnimationController能夠在XML中設置,也可在Java代碼中設置

先看一個在XML中設置的Demo(AnimationDemo04)

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:duration="2000"
        android:fromAlpha="0.0"
        android:toAlpha="1.0" />
</set>
list_anim_layout.xml
<?xml version="1.0" encoding="utf-8"?>
<layoutAnimation xmlns:android="http://schemas.android.com/apk/res/android"
    android:delay="1"
    android:animationOrder="normal"
    android:animation="@anim/list_anim" />
main.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" >
    <ListView
        android:id="@id/android:list"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layoutAnimation="@anim/list_anim_layout"
        android:scrollbars="vertical"
        android:visibility="gone" />
    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:gravity="bottom"
        android:orientation="vertical" >
        <Button
            android:id="@+id/button"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:text="測試LayoutAnimation動畫效果" />
    </LinearLayout>
</LinearLayout>
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:paddingBottom="1dip"
    android:paddingLeft="10dip"
    android:paddingRight="10dip"
    android:paddingTop="1dip" >
    <TextView
        android:id="@+id/user_name"
        android:layout_width="180dip"
        android:layout_height="30dip"
        android:singleLine="true"
        android:textSize="20dip" />
    <TextView
        android:id="@+id/user_gender"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:singleLine="true"
        android:textSize="20dip" />
</LinearLayout>
AnimationDemoActivity.java
package com.tianjf;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import android.app.ListActivity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
public class AnimationDemoActivity extends ListActivity implements OnClickListener {
    private ListView mListView;
    private Button mButton;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        mListView = getListView();
        mButton = (Button) findViewById(R.id.button);
        mListView.setAdapter(buildListAdapter());
        mButton.setOnClickListener(this);
    }
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
        case R.id.button:
            mListView.setVisibility(View.VISIBLE);
            break;
        default:
            break;
        }
    }
    private ListAdapter buildListAdapter() {
        List<HashMap<String, String>> list = new ArrayList<HashMap<String, String>>();
        HashMap<String, String> m1 = new HashMap<String, String>();
        m1.put("user_name", "張三");
        m1.put("user_gender", "女");
        HashMap<String, String> m2 = new HashMap<String, String>();
        m2.put("user_name", "李四");
        m2.put("user_gender", "女");
        HashMap<String, String> m3 = new HashMap<String, String>();
        m3.put("user_name", "王五");
        m3.put("user_gender", "男");
        list.add(m1);
        list.add(m2);
        list.add(m3);
        SimpleAdapter simpleAdapter = new SimpleAdapter(this, list, R.layout.item, new String[] {
                "user_name", "user_gender" }, new int[] { R.id.user_name, R.id.user_gender });
        return simpleAdapter;
    }
}
layoutAnimation標籤中的android:animationOrder屬性就是設置動畫的顯示順序的,normal就是依次顯示出來


若是要在Java代碼中設置LayoutAnimation,能夠按照以下設置

刪掉list_anim_layout.xml文件,刪掉main.xml下的ListView的android:layoutAnimation屬性,最後,在OnClick方法裏面加上以下代碼:

Animation animation = (Animation) AnimationUtils.loadAnimation(this, R.anim.list_anim);
LayoutAnimationController lac = new LayoutAnimationController(animation);
lac.setOrder(LayoutAnimationController.ORDER_NORMAL);
lac.setDelay(0.5f);
mListView.setLayoutAnimation(lac);


4、AnimationListener

還能夠爲Animation對象添加AnimationListener監聽器。監聽動畫執行的各階段。


AnimationListener主要包含三個方法:

  1. onAnimationEnd:動畫結束

  2. onAnimationStart:動畫開始

  3. onAnimationRepet:動畫重複


原文: http://blog.csdn.net/tianjf0514/article/details/7566304

相關文章
相關標籤/搜索