標籤:java animation android 開源項目 原始碼
前言、動畫分類
如所示,Android的動畫主要分為三種:
下面首先說說屬性動畫
所謂屬性動畫——就是指對象的屬性值發生了變化,如控制項位置和透明度等。
舉例,現在要實現一個按鍵先下移,再右移的動畫。
(1)編寫動畫xml
由於建立android工程的時候,在res下面並沒有專門放置動畫xml的檔案夾,因此,我們建立一個animator名稱的檔案夾。建議不要起別的名字,因為ADT對res的檔案夾命名有檢索功能,如起animator這個名字的時候,ADT就能根據名稱識別出這個是動畫xml檔案夾,在你建立xml的時候,會給相應的根項目選擇。
如所示:
動畫XML的代碼如下——
<?xml version="1.0" encoding="utf-8"?><set xmlns:android="http://schemas.android.com/apk/res/android" android:ordering="sequentially" > <objectAnimator android:duration="2000" android:propertyName="y" android:valueTo="500" android:valueType="intType"></objectAnimator> <objectAnimator android:duration="2000" android:propertyName="a" android:valueTo="300" android:valueType="intType"></objectAnimator></set>
對動畫xml的說明如下:
- android:ordering說明一系列動畫動作的執行順序,有兩個選擇,sequentially和together,順序執行還是一起執行;
- objectAnimator是設定動畫實施的對象,duration是該動畫動作執行從開始到結束所用的時間,屬性是y(後面在Activity會講到,這是自己定義的屬性,用來指button的在螢幕中的y座標值。),屬性值是500,類型是整型。
(2)Activity代碼
public class PropertyActivity extends Activity {public final static String TAG = "PropertyActivity";@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_property);final Button moveButton = (Button)findViewById(R.id.move_btn);final Move move = new Move(moveButton);moveButton.setOnClickListener(new OnClickListener() {@Overridepublic void onClick(View v) {// 裝載屬性動畫資源AnimatorSet set = (AnimatorSet) AnimatorInflater.loadAnimator(PropertyActivity.this,R.animator.property_anim);// 設定要控制的對象set.setTarget(move);// 開始動畫set.start();Log.d(TAG, "getWidth:"+moveButton.getWidth());Log.d(TAG, "Top:"+moveButton.getTop());Log.d(TAG, "getMeasuredWidth:"+moveButton.getMeasuredWidth());Log.d(TAG, "getBottom:"+moveButton.getBottom());}});}private class Move{ private int a; private int y; private View view; public Move(View view) { this.view = view;} public int getY(){ return y;}public void setY(int y){this.y = y;view.layout(view.getLeft(), y, view.getRight(),y + view.getMeasuredHeight());}public int getA(){return a;}public void setA(int a){this.a = a;Log.d(TAG, "End_getWidth:"+view.getWidth());Log.d(TAG, "End_Top:"+view.getTop());Log.d(TAG, "End_getMeasuredWidth:"+view.getMeasuredWidth());Log.d(TAG, "End_getBottom:"+view.getBottom());view.layout(a, view.getTop(), a + view.getMeasuredWidth(),view.getBottom());} }}
我們在程式中Logcat列印出對button位置的具體值。
Log.d(TAG,"getWidth:"+moveButton.getWidth());
Log.d(TAG,"Top:"+moveButton.getTop());
Log.d(TAG,"getMeasuredWidth:"+moveButton.getMeasuredWidth());
Log.d(TAG,"getBottom:"+moveButton.getBottom());
結果如下:
上下高度確實是從0變化到500,實現了移動。
上面代碼中的屬性x,y都是自己任意取的變數值,在set方法中設定了具體view的高度和寬度,因此,變數名稱是什麼不重要,只要xml與這裡java代碼相符合就行。 get()方法不是必需的,而set方法是必須的,因為
AnimatorSet動畫設定類中就需要調用對象的屬性設定方法,通過動畫來改變相應屬性。
以上只是簡單地示範了屬性動畫,實際上這個是從Android 3.0後才出來的,3.0之前有一個很著名的動畫開源項目,名字叫做 Nine Old Androids ,該項目開發了很多屬性動畫, 如所示,不好意思,不會做gif動態圖。大家可以直接在博文後面的連結下,裡面有APK和原始碼。值得一讀。
開源項目Nine Old Androids 資料