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

Material Design 自定義動畫全解:從觸摸波紋到向量圖動畫

編輯:關於 Android 程式設計

Android 5.0 引入的新動畫 API,讓你能為 UI 元件加入觸摸回饋、狀態切換與 Activity 轉場等效果,具體涵蓋:

  • 回應 View 觸摸事件的波紋反饋動畫
  • 顯示與隱藏 View 的循環揭示動畫
  • 兩個 Activity 之間的切換動畫
  • 更自然的曲線運動
  • 依 View 狀態變更而改變屬性的動畫
  • 狀態改變時播放的狀態清單動畫

這些 API 已內建於 Button 等標準元件中,自訂 View 時同樣可以取用。

在 Material 的語彙裡,動畫不只是裝飾,它承擔著回饋使用者操作、維持視覺連續性的責任。Material 主題已為按鈕與 Activity 轉場備好預設動畫,而在 API 21 以上,你可以自訂:觸摸回饋、循環顯示、Activity 轉場、曲線運動、View 狀態變化。

自定義觸摸回饋

波紋效果由 RippleDrawable 實作,在多數情況下你只要在布局中指定背景即可:

  • android:attr/selectableItemBackground:有邊界的波紋
  • android:attr/selectableItemBackgroundBorderless:可溢出 View 邊界的波紋(API 21 新增)

也可以自行撰寫 RippleDrawable 的 XML 資源。想改變預設波紋顏色,覆寫主題的 android:colorControlHighlight 屬性即可。

循環揭示效果

ViewAnimationUtils.createCircularReveal() 能讓一個 View 以圓形向外擴散的方式出現或消失。

 // previously invisible view View myView = findViewById(R.id.my_view); // get the center for the clipping circle int cx = (myView.getLeft() + myView.getRight()) / 2; int cy = (myView.getTop() + myView.getBottom()) / 2; // get the final radius for the clipping circle int finalRadius = myView.getWidth(); // create and start the animator for this view // (the start radius is zero) Animator anim = ViewAnimationUtils.createCircularReveal(myView, cx, cy, 0, finalRadius); anim.start(); 隱藏 // previously visible view final View myView = findViewById(R.id.my_view); // get the center for the clipping circle int cx = (myView.getLeft() + myView.getRight()) / 2; int cy = (myView.getTop() + myView.getBottom()) / 2; // get the initial radius for the clipping circle int initialRadius = myView.getWidth(); // create the animation (the final radius is zero) Animator anim = ViewAnimationUtils.createCircularReveal(myView, cx, cy, initialRadius, 0); // make the view invisible when the animation is done anim.addListener(new AnimatorListenerAdapter() { @Override public void onAnimationEnd(Animator animation) { super.onAnimationEnd(animation); myView.setVisibility(View.INVISIBLE); } }); // start the animation anim.start(); 

Activity 轉場

轉場可分成三種角色:

  • enter transition:Activity 進場的方式,例如 explode 讓 View 從外側飛向螢幕中心。
  • exit transition:Activity 退場的方式,例如 explode 讓 View 從中心散去。
  • shared element transition:兩個 Activity 共享同一元素時的平滑轉換,例如同一張圖片位置與尺寸不同,用 changeImageTransform 就能讓它連續地移動與縮放。

API 21 以上內建 Explode、Slide、Fade 三種轉場,以及 changeBounds(邊界變化)、changeClipBounds(裁剪邊界變化)、changeTransform(旋轉與縮放變化)、changeImageTransform(圖片尺寸與縮放變化)等共享元素轉換。啟用後,進入與退出預設會以淡入淡出搭配呈現。

宣告式設定

 <?xml version="1.0" encoding="utf-8"?> <resources> <style name="MyTheme" parent="@android:style/Theme.Material"> <!-- enable window content transitions --> <item name="android:windowContentTransitions">true</item> <!-- specify enter and exit transitions --> <item name="android:windowEnterTransition">@android:transition/explode</item> <item name="android:windowExitTransition">@android:transition/explode</item> <!-- specify shared element transitions --> <item name="android:windowSharedElementEnterTransition">@android:transition/move</item> <item name="android:windowSharedElementExitTransition">@android:transition/slide_top</item> </style> </resources> 

每個 transition 的 XML 檔案,內容其實就是「這次要一起變化的屬性集合」。程式碼中也能啟用:

 // inside your activity (if you did not enable transitions in your theme) getWindow().requestFeature(Window.FEATURE_CONTENT_TRANSITIONS); // set an exit transition getWindow().setExitTransition(new Explode()); 

相關的設定方法還有 Window.setEnterTransition()、setExitTransition()、setSharedElementEnterTransition()、setSharedElementExitTransition();若想讓進出動畫重疊以加快節奏,可呼叫 Window.setAllowEnterTransitionOverlap()。

啟動帶轉場的 Activity

 startActivity(intent, ActivityOptions.makeSceneTransitionAnimation(this).toBundle());

若不想套用轉場,第二個參數傳 null 即可:

 startActivity(intent,null); //傳遞null 的options bundle 

單一共享元素

  1. 於主題中啟用 window content transitions。
  2. 在 style 中定義共享元素的轉場。
  3. 在 res/transition 建立 transition 的 XML 資源。
  4. 在布局中以 android:transitionName 標記第 3 步使用的名稱。
  5. 呼叫 ActivityOptions.makeSceneTransitionAnimation() 產生 options 物件。
 // get the element that receives the click event final View imgContainerView = findViewById(R.id.img_container); // get the common element for the transition in this activity final View androidRobotView = findViewById(R.id.image_small); // define a click listener imgContainerView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent intent = new Intent(this, Activity2.class); // create the transition animation - the images in the layouts // of both activities are defined with android:transitionName="robot" ActivityOptions options = ActivityOptions .makeSceneTransitionAnimation(this, androidRobotView, "robot"); // start the new activity startActivity(intent, options.toBundle()); } });

程式碼中也可用 View.setTransitionName() 完成同樣的標記。另外,關閉第二個 Activity 時若想播放反向動畫,請改用 Activity.finishAfterTransition() 而非 finish()。

多個共享元素

 ActivityOptions options = ActivityOptions.makeSceneTransitionAnimation(this, Pair.create(view1, "agreedName1"), Pair.create(view2, "agreedName2"));

曲線運動

Material 的動畫建立在曲線式的時間插值與空間路徑之上。API 21 起,時間曲線與運動路徑都能自訂。PathInterpolator 是新的插值器,可基於貝茲曲線或 Path 物件建構,其運動曲線定義在一個 1×1 的正方形中,以 (0,0) 為錨點、(1,1) 為終點。

 <pathInterpolator xmlns:android="https://schemas.android.com/apk/res/android" android:controlX1="0.4" android:controlY1="0" android:controlX2="1" android:controlY2="1"/> 

系統內建三條常用曲線:@interpolator/fast_out_linear_in、fast_out_slow_in、linear_out_slow_in。把 PathInterpolator 傳給 Animator.setInterpolator() 即可套用。此外,ObjectAnimator 新增了建構方式,能讓同一個路徑同時驅動多個屬性:

 ObjectAnimator mAnimator; mAnimator = ObjectAnimator.ofFloat(view, View.X, View.Y, path); ... mAnimator.start(); 

View 狀態變化動畫

StateListAnimator 讓你能宣告「在某狀態下播放某動畫」:

 <!-- animate the translationZ property of a view when pressed --> <selector xmlns:android="https://schemas.android.com/apk/res/android"> <item android:state_pressed="true"> <set> <objectAnimator android:propertyName="translationZ" android:duration="@android:integer/config_shortAnimTime" android:valueTo="2dp" android:valueType="floatType"/> <!-- you could have other objectAnimator elements here for "x" and "y", or other properties --> </set> </item> <item android:state_enabled="true" android:state_pressed="false" android:state_focused="true"> <set> <objectAnimator android:propertyName="translationZ" android:duration="100" android:valueTo="0" android:valueType="floatType"/> </set> </item> </selector> 

把這份資源指派給 View 的 android:stateListAnimator;程式碼中則用 AnimationInflater.loadStateListAnimator() 載入,再交給 View.setStateListAnimator()。若主題繼承 Material,按鈕預設就帶有 Z 動畫,不想要的話把 android:stateListAnimator 設為 null 即可。

AnimatedStateListDrawable 則讓 Drawable 本身具備狀態轉換動畫,5.0 上部分系統元件已預設採用:

 <!-- res/drawable/myanimstatedrawable.xml --> <animated-selector xmlns:android="https://schemas.android.com/apk/res/android"> <!-- provide a different drawable for each state--> <item android:id="@+id/pressed" android:drawable="@drawable/drawableP" android:state_pressed="true"/> <item android:id="@+id/focused" android:drawable="@drawable/drawableF" android:state_focused="true"/> <item android:id="@id/default" android:drawable="@drawable/drawableD"/> <!-- specify a transition --> <transition android:fromId="@+id/default" android:toId="@+id/pressed"> <animation-list> <item android:duration="15" android:drawable="@drawable/dt1"/> <item android:duration="15" android:drawable="@drawable/dt2"/> ... </animation-list> </transition> ... </animated-selector> 

向量圖動畫

向量圖放大不失真,而 AnimatedVectorDrawable 能讓它動起來。通常需要三份 XML:放在 res/drawable/ 的 <vector>、同樣放在 res/drawable/ 的 <animated-vector>,以及放在 res/animator/ 或 res/anim/ 的 object animator。

向量圖由 <group> 與 <path> 組成:group 是 path 或子 group 的集合,path 描述實際繪製的路徑。定義時可為兩者命名,供動畫引用:

 <!-- res/drawable/vectordrawable.xml --> <vector xmlns:android="https://schemas.android.com/apk/res/android" android:height="64dp" android:width="64dp" android:viewportHeight="600" android:viewportWidth="600"> <group android:name="rotationGroup" android:pivotX="300.0" android:pivotY="300.0" android:rotation="45.0" > <path android:name="v" android:fillColor="#000000" android:pathData="M300,70 l 0,-70 70,70 0,0 -70,70z" /> </group> </vector> 
 <!-- res/drawable/animvectordrawable.xml --> <animated-vector xmlns:android="https://schemas.android.com/apk/res/android" android:drawable="@drawable/vectordrawable" > <target android:name="rotationGroup" android:animation="@anim/rotation" /> <target android:name="v" android:animation="@anim/path_morph" /> </animated-vector> 

例如讓 group 旋轉一圈:

 <!-- res/anim/rotation.xml --> <objectAnimator android:duration="6000" android:propertyName="rotation" android:valueFrom="0" android:valueTo="360" /> 

而路徑變形(morph)有個硬性條件:起點與終點路徑必須擁有相同數量的指令,且每個指令的參數個數一致,否則無法插值。

 <!-- res/anim/path_morph.xml --> <set xmlns:android="https://schemas.android.com/apk/res/android"> <objectAnimator android:duration="3000" android:propertyName="pathData" android:valueFrom="M300,70 l 0,-70 70,70 0,0 -70,70z" android:valueTo="M300,70 l 0,-70 70,0 0,140 -70,0 z" android:valueType="pathType" /> </set> 
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved