編輯:Android 開發教學
在上一篇文章中,我和大家一起實現了類似 Android 系統聯絡人的分組導航與擠壓動畫功能。不過,既然文章名叫《Android 系統聯絡人全特效實現》,那麼少了快速滾動功能,顯然就配不上「全」這個字。因此,本文將帶領大家在上篇文章的程式碼基礎上加以改進,加入快速滾動功能。
如果還沒看過上一篇文章,請抓緊去閱讀《Android 系統聯絡人全特效實現(上):分組導航和擠壓動畫》。
其實 ListView 本身就有一個快速滾動屬性,可以透過在 XML 中設定 android:fastScrollEnabled="true" 來啟用。包括以前舊版本的 Android 聯絡人,都是用這種方式來做快速滾動的,效果如下圖:

不過這種快速滾動方式比較美觀不足,後來許多手機廠商在定製自己 ROM 時,都將預設的快速滾動改成了類似 iPhone 上 A-Z 字母表快速滾動的方式。這裡我們怎能落後於時代的潮流呢!我們的快速滾動也要採用 A-Z 字母表的方式!
下面就來開始實作。首先打開上次的 ContactsDemo 專案,修改 activity_main.xml 佈局檔。由於我們要在界面上加入字母表,所以需要一個 Button,把它的背景設為一張 A-Z 排序的圖片,並靠右對齊;另外還需要一個 TextView,用於在彈出式分組佈局上顯示目前的分組,預設是 gone 掉的,只有手指在字母表上滑動時才讓它顯示出來。修改後的佈局檔程式碼如下:
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android" xmlns:tools="https://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" > <ListView android:id="@+id/contacts_list_view" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_alignParentTop="true" android:scrollbars="none" android:fadingEdge="none" > </ListView> <LinearLayout android:id="@+id/title_layout" android:layout_width="fill_parent" android:layout_height="18dip" android:layout_alignParentTop="true" android:background="#303030" > <TextView android:id="@+id/title" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center_horizontal" android:layout_marginLeft="10dip" android:textColor="#ffffff" android:textSize="13sp" /> </LinearLayout> <Button android:id="@+id/alphabetButton" android:layout_width="wrap_content" android:layout_height="fill_parent" android:layout_alignParentRight="true" android:background="@drawable/a_z" /> <RelativeLayout android:id="@+id/section_toast_layout" android:layout_width="70dip" android:layout_height="70dip" android:layout_centerInParent="true" android:background="@drawable/section_toast" android:visibility="gone" > <TextView android:id="@+id/section_toast_text" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerInParent="true" android:textColor="#fff" android:textSize="30sp" /> </RelativeLayout> </RelativeLayout>
佈局就緒後,後續只要在程式碼中為字母表 Button 綁定觸摸事件,依滑動位置換算字母、呼叫 ListView 的 setSelection 定位,並同步更新中央提示的 TextView,就能實現媲美系統聯絡人的字母表快速滾動特效。
閱讀 Android 源碼的心得:版本、Linux 與工具準備
研究 Android 源碼不能只看單一版本。對照舊版本與新版本,能更清楚理解系統模組如何演進,例如 SurfaceView 相關操作在後期被拆分到 SurfaceCont
Android WebView 基本用法:在 Activity 中載入網頁
WebView 可在 Activity 中嵌入瀏覽器,適合顯示網頁內容或網路圖表。使用時於版面配置加入 WebView,再在程式碼中載入網址。必要設定若網頁需要縮放,可啟
Android 自定義控件進階(八):滑動效果與自定義屬性
自定義控件常用的有 View、ViewGroup、Scroller 三個類別,其繼承關係如下: 本示例自定義了一個控件,實現類似 Gallery 的效果,並額外加上一條
Android 聯絡人全特效實現:分組導航與擠壓動畫
Android 系統聯絡人會依姓氏或拼音分組,並在頂部顯示目前群組。當新群組接近前一群組時,還會出現上頂的擠壓動畫,讓滾動更有層次感。實作這類效果,可利用 Section