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

Animation 應用於 Layout:讓 ListView 逐項進場

編輯:關於 Android 程式設計

前面幾篇談的多是單一 View 的動畫,這次換個角度:把動畫套在「整個 Layout」上,讓 ListView 的每一項依序出現。以 ListView 為例,實作方式有兩種——XML 宣告與純程式碼。

方式一:在 XML 中宣告 layoutAnimation

首先在 res/anim 下定義動畫本身,例如 anim_list.xml:

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="https://schemas.android.com/apk/res/android"
    android:interpolator="@android:anim/accelerate_interpolator">
    <alpha
        android:duration="2000"
        android:fromAlpha="0.0"
        android:toAlpha="1.0" />
</set>

接著定義「如何套用到 Layout 上」,layout_anim_list.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/anim_list">
</layoutAnimation>

最後在 ListView 標籤上掛一行屬性即可:

android:layoutAnimation="@anim/layout_anim_list"

三個屬性中,delay 控制每個子項之間的間隔倍率,animationOrder 決定播放順序(normal / reverse / random),animation 指向真正要套用的動畫資源。

方式二:用 LayoutAnimationController 以程式碼設定

// 先設定資料
listView.setAdapter(buildListAdapter());

Animation animation = AnimationUtils.loadAnimation(MainActivity.this, R.anim.anim_list);
// 建立控制器,第二個參數為子項間的延遲比例
LayoutAnimationController lac = new LayoutAnimationController(animation, 0.5f);
lac.setOrder(LayoutAnimationController.ORDER_NORMAL);
listView.setLayoutAnimation(lac);

核心就是把 Animation 與延遲值包進 LayoutAnimationController,再交給 View 的 setLayoutAnimation()。兩種方式效果等價,XML 適合固定不變的動畫,程式碼則方便依條件動態切換。

版面配置

主佈局 main.xml 用 RelativeLayout 依序排出標題、ListView 與觸發按鈕:

<TextView
    android:id="@+id/myText"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/hello_world" />

<ListView
    android:id="@+id/myList"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_below="@id/myText" />

<Button
    android:id="@+id/myButton"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_below="@id/myList"
    android:text="測試" />

列表項 item.xml 則是橫向的 LinearLayout,放兩個 TextView 分別顯示 user 與 sex。

資料綁定

private ListAdapter buildListAdapter() {
    ArrayList<HashMap<String, String>> list = new ArrayList<HashMap<String, String>>();
    HashMap<String, String> map1 = new HashMap<String, String>();
    map1.put("user", "張三");
    map1.put("sex", "男");
    // map2、map3 同理略
    list.add(map1);
    return new SimpleAdapter(MainActivity.this, list, R.layout.item,
            new String[]{"user", "sex"}, new int[]{R.id.user, R.id.sex});
}

點擊按鈕後重新 setAdapter 並套用 LayoutAnimation,就能看到列表項一個接一個淡入的進場效果。若改用 XML 宣告方式,則把程式碼中的 setAdapter 與控制器那段註解掉即可,效果相同。

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