編輯:關於 Android 程式設計
前面幾篇談的多是單一 View 的動畫,這次換個角度:把動畫套在「整個 Layout」上,讓 ListView 的每一項依序出現。以 ListView 為例,實作方式有兩種——XML 宣告與純程式碼。
首先在 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 指向真正要套用的動畫資源。
// 先設定資料 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 與控制器那段註解掉即可,效果相同。
Android Volley 網路請求入門:快速上手 Google 官方網路庫
Volley 是什麼Volley 是 Google 在 I/O 大會上推出的 Android 網路通訊庫,主要目標是讓網路請求變得更簡單、更快速,也更穩定。過去開發者在處
用 ProgressDialog 為耗時操作加上進度提示
這篇延續上一篇「讀取聯絡人資訊」的程式碼繼續寫。在做聯絡人遍歷的時候我發現,用 Cursor 一筆一筆取出所有聯絡人的資料其實挺慢的——我手機上不到四百筆聯絡方式,完整跑
啟動動畫實作:告別生硬冷啟動
所謂冷啟動(Cold Start),指的是應用被完全關閉後重新開啟、系統直接拋出首屏的那一瞬間。畫面「啪」地出現,用戶往往還沒反應過來。與其如此,不如在啟動時鋪一段簡短的
自定義 View 實作:隨音量變化的圓形錄音按鈕
所謂無圖無真相,先來看效果圖。我們要實現的,是中間那個錄音按鈕——其周邊會顯示一圈隨音量大小變化的波形。 設計思路 VolumCircleBar 繼承自 View,透