編輯:關於 Android 程式設計
Android 5.0 引入的新動畫 API,讓你能為 UI 元件加入觸摸回饋、狀態切換與 Activity 轉場等效果,具體涵蓋:
這些 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();
轉場可分成三種角色:
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()。
startActivity(intent, ActivityOptions.makeSceneTransitionAnimation(this).toBundle());
若不想套用轉場,第二個參數傳 null 即可:
startActivity(intent,null); //傳遞null 的options bundle
res/transition 建立 transition 的 XML 資源。android:transitionName 標記第 3 步使用的名稱。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();
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>
用 RoundedBitmapDrawable 產生圓角與圓形圖片
RoundedBitmapDrawable 是官方提供的 Drawable 子類,能直接把一張 Bitmap 轉成帶圓角的樣子,省去自己寫 Canvas 裁切的麻煩。最
Android TableLayout 常用屬性介紹
collapseColumnscollapseColumns 可依列索引隱藏指定欄位。若不設定此屬性,表格會完整顯示。若設定為 0,2,則第 0 與第 2 欄會被隱藏。s
Android 實現 ListView 點擊展開/收合的第二種點擊收合效果
做電商專案的優惠券頁面時遇到這樣的需求:列表分「未使用」與「已使用」兩頁,點擊某個 item 時把它下方的刪除按鈕展開;點擊其他 item 時,先前展開的那筆要收起來,被
Android 中 ListView 結合 CheckBox 實作資料批量選擇(全選、反選、全不選)
在 App 開發中,經常會遇到這樣的需求:批量取消(刪除)List 中的資料。這就要求 ListView 支援批量選擇、全選、單選等功能,因此打造一個功能完善的 List