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

Android 動畫(五):LayoutAnimationController 讓列表逐項登場

編輯:關於 Android 程式設計

LayoutAnimationController 能讓一個容器中的子控制項「依序」出現,而不是整批同時現身。清單逐項淡入、網格依序彈出,都是靠它。實作有 XML 與程式碼兩條路。

做法一:純 XML 宣告

第一步,在 res 下建立 anim 目錄,新增 alpha.xml 定義單項的動畫:

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="https://schemas.android.com/apk/res/android"
    android:interpolator="@android:anim/accelerate_interpolator"
    android:shareInterpolator="true">

    <alpha
        android:fromAlpha="0"
        android:toAlpha="1"
        android:duration="3000" />
</set>

第二步,在同一目錄新增 layoutanimation.xml,定義「怎麼排隊」:

<?xml version="1.0" encoding="utf-8"?>
<layoutAnimation
    xmlns:android="https://schemas.android.com/apk/res/android"
    android:delay="0.5"
    android:animationOrder="normal"
    android:animation="@anim/alpha" />

其中 delay 是每個子項之間的延遲比例(0.5 表示每項延後前一项動畫時長的 0.5 倍),animationOrder 決定播放順序。

第三步,在 ListView 上掛上它:

<ListView
    android:id="@+id/listView1"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layoutAnimation="@anim/layoutanimation" />

做法二:程式碼動態設定

AlphaAnimation alpha = new AlphaAnimation(0, 1);
alpha.setDuration(3000);

LayoutAnimationController lac = new LayoutAnimationController(alpha);
lac.setOrder(LayoutAnimationController.ORDER_NORMAL);

lv.setLayoutAnimation(lac);

三種播放順序

LayoutAnimationController.ORDER_NORMAL;   // 順序顯示
LayoutAnimationController.ORDER_REVERSE;  // 反向顯示
LayoutAnimationController.ORDER_RANDOM;   // 隨機顯示

實務提醒

LayoutAnimationController 只在容器首次配置子檢視時生效。因此如果是 ListView 這種會回收重用的檢視,捲動時新項目的進場動畫不會自動重跑;反之,若你每次 notifyDataSetChanged 都重新觸發,捲動過程可能會變得卡頓。想要「捲動時每項都有進場效果」,通常得在 getView 中自行控制,或改用 ItemAnimator/自訂 LayoutTransition。

另外,delay 是「相對比例」而非絕對毫秒。動畫時長設 3000ms、delay 設 0.5,十個項目就要排到數秒之久,實務上通常會把單項 duration 壓到兩三百毫秒,delay 取 0.1~0.3,整體節奏才不會拖沓。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved