編輯:Android 開發實例
剛入門 Android 的那段日子,我對系統通訊錄裡的一個小細節特別著迷:它會依照每個聯絡人姓氏的拼音首字母自動分組,並在螢幕最上方固定顯示目前所處的分組標籤。如下圖所示:
而最令我愛不釋手的,是當下一個分組逐漸逼近並與前一個分組相撞時,頂部標籤會被緩緩向上推擠的那段過場動畫。那時我嘗試過各種思路想把它做出來,無奈功力尚淺,屢屢碰壁。一晃兩年多過去,自己也磨練了不少,某天回頭再想這個功能,思路竟豁然開朗,於是趕緊記錄下來與各位分享。
先談談需要具備的基礎知識。這裡最核心的工具是 SectionIndexer,它能幫我們輕鬆掌控分組邏輯。SectionIndexer 本身是一個介面,你可以自訂子類別來實作它;但從零打造一個實作過於繁瑣,好在 Android 已經提供了現成的 AlphabetIndexer,拿來做聯絡人分組綽綽有餘。
AlphabetIndexer 的建構子需要三個參數:第一個是 cursor(游標),第二個是 sortedColumnIndex(排序所在的欄位索引),第三個是 alphabet(字母排序規則的字串)。cursor 就是從資料庫查詢回來的游標;sortedColumnIndex 用來指明以哪一欄作為排序依據;alphabet 則是排序字母表,例如 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"。有了 AlphabetIndexer,我們就能透過 getPositionForSection 與 getSectionForPosition 這兩個方法,在「位置」與「分組」之間互相換算,進而還原出系統通訊錄那種分組導航與擠壓動畫。更細節的用法可參考官方文件。
那麼,聯絡人究竟該怎麼排序呢?前面提到過 sortedColumnIndex 這個參數,可這個排序欄位到底在哪裡?我們來看看系統通訊錄的 raw_contacts 資料表(/data/data/com.android.providers.contacts/databases/contacts2.db)。這張表結構相當複雜,光是欄位就有二十多個,其中有一欄名為 sort_key,正是我們要找的寶貝。如下圖所示:
可以看到,這一欄貼心地替我們記錄了每個漢字對應的拼音,於是排序聯絡人變得輕而易舉。
準備工作說完,我們正式動手。新建一個名為 ContactsDemo 的 Android 專案,先來完成布局。打開或建立 activity_main.xml 作為主布局,寫入以下程式碼:
- <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: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>
- </RelativeLayout>
這個布局並不複雜:一個 ListView 負責呈現聯絡人清單,頂部再疊放一個 LinearLayout,內含一個 TextView,用來在介面上方常駐顯示目前的分組字母。
接著新建 contact_item.xml,作為 ListView 每一列的填充模板,程式碼如下:
- <LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
- android:layout_width="match_parent"
- android:layout_height="match_parent"
- android:orientation="vertical" >
- <LinearLayout
- android:id="@+id/sort_key_layout"
- android:layout_width="fill_parent"
- android:layout_height="18dip"
- android:background="#303030" >
- <TextView
- android:id="@+id/sort_key"
- 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>
- <LinearLayout
- android:id="@+id/name_layout"
- android:layout_width="fill_parent"
- android:layout_height="50dip" >
- <ImageView
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:layout_gravity="center_vertical"
- android:layout_marginLeft="10dip"
- android:layout_marginRight="10dip"
- android:src="@drawable/icon" />
- <TextView
- android:id="@+id/name"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:layout_gravity="center_vertical"
- android:textColor="#ffffff"
- android:textSize="22sp" />
- </LinearLayout>
- </LinearLayout>
這個模板的設計思路很清楚:頂部同樣放一個分組標籤布局,因為除了介面上方,每個分組的第一個項目之前也需要顯示分組;下方則是一個簡單的 LinearLayout,內含顯示頭像的 ImageView 與顯示姓名的 TextView。
布局部分到此全部搞定,接下來才是真正的功能實作。
先從最簡單的 Contact 實體類開始:
- public class Contact {
- /**
- * 聯系人姓名
- */
- private String name;
- /**
- * 排序字母
- */
- private String sortKey;
- public String getName() {
- return name;
- }
- public void setName(String name) {
- this.name = name;
- }
- public String getSortKey() {
- return sortKey;
- }
- public void setSortKey(String sortKey) {
- this.sortKey = sortKey;
- }
- }
這個類別只承載聯絡人姓名與排序鍵,非常輕量。
再來撰寫聯絡人清單的適配器。新建 ContactAdapter 類別並繼承 ArrayAdapter:
- public class ContactAdapter extends ArrayAdapter<Contact> {
- /**
- * 需要渲染的item布局文件
- */
- private int resource;
- /**
- * 字母表分組工具
- */
- private SectionIndexer mIndexer;
- public ContactAdapter(Context context, int textViewResourceId, List<Contact> objects) {
- super(context, textViewResourceId, objects);
- resource = textViewResourceId;
- }
- @Override
- public View getView(int position, View convertView, ViewGroup parent) {
- Contact contact = getItem(position);
- LinearLayout layout = null;
- if (convertView == null) {
- layout = (LinearLayout) LayoutInflater.from(getContext()).inflate(resource, null);
- } else {
- layout = (LinearLayout) convertView;
- }
- TextView name = (TextView) layout.findViewById(R.id.name);
- LinearLayout sortKeyLayout = (LinearLayout) layout.findViewById(R.id.sort_key_layout);
- TextView sortKey = (TextView) layout.findViewById(R.id.sort_key);
- name.setText(contact.getName());
- int section = mIndexer.getSectionForPosition(position);
- if (position == mIndexer.getPositionForSection(section)) {
- sortKey.setText(contact.getSortKey());
- sortKeyLayout.setVisibility(View.VISIBLE);
- } else {
- sortKeyLayout.setVisibility(View.GONE);
- }
- return layout;
- }
- /**
- * 給當前適配器傳入一個分組工具。
- *
- * @param indexer
- */
- public void setIndexer(SectionIndexer indexer) {
- mIndexer = indexer;
- }
- }
這段程式碼的靈魂在 getView 方法。我們先用 getSectionForPosition 依當前 position 取得對應的 section,再用這個 section 反查 getPositionForSection 得到新的 position。若兩個 position 相等,就代表目前這項是某個分組的第一個元素,此時顯示分組標籤;否則一律隱藏。這正是分組標籤只出現在每組開頭的關鍵。
最後來寫主介面。打開或建立 MainActivity:
- public class MainActivity extends Activity {
- /**
- * 分組的布局
- */
- private LinearLayout titleLayout;
- /**
- * 分組上顯示的字母
- */
- private TextView title;
- /**
- * 聯系人ListView
- */
- private ListView contactsListView;
- /**
- * 聯系人列表適配器
- */
- private ContactAdapter adapter;
- /**
- * 用于进行字母表分组
- */
- private AlphabetIndexer indexer;
- /**
- * 存儲所有手機中的聯系人
- */
- private List<Contact> contacts = new ArrayList<Contact>();
- /**
- * 定義字母表的排序規則
- */
- private String alphabet = "#ABCDEFGHIJKLMNOPQRSTUVWXYZ";
- /**
- * 上次第一個可見元素,用于滚动时记录标识。
- */
- private int lastFirstVisibleItem = -1;
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.activity_main);
- adapter = new ContactAdapter(this, R.layout.contact_item, contacts);
- titleLayout = (LinearLayout) findViewById(R.id.title_layout);
- title = (TextView) findViewById(R.id.title);
- contactsListView = (ListView) findViewById(R.id.contacts_list_view);
- Uri uri = ContactsContract.CommonDataKinds.Phone.CONTENT_URI;
- Cursor cursor = getContentResolver().query(uri,
- new String[] { "display_name", "sort_key" }, null, null, "sort_key");
- if (cursor.moveToFirst()) {
- do {
- String name = cursor.getString(0);
- String sortKey = getSortKey(cursor.getString(1));
- Contact contact = new Contact();
- contact.setName(name);
- contact.setSortKey(sortKey);
- contacts.add(contact);
- } while (cursor.moveToNext());
- }
- startManagingCursor(cursor);
- indexer = new AlphabetIndexer(cursor, 1, alphabet);
- adapter.setIndexer(indexer);
- if (contacts.size() > 0) {
- setupContactsListView();
- }
- }
- /**
- * 为联系人ListView设置监听事件,根据当前的滑动状态来改变分组的显示位置,从而实现挤压动画的效果。
- */
- private void setupContactsListView() {
- contactsListView.setAdapter(adapter);
- contactsListView.setOnScrollListener(new OnScrollListener() {
- @Override
- public void onScrollStateChanged(AbsListView view, int scrollState) {
- }
- @Override
- public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount,
- int totalItemCount) {
- int section = indexer.getSectionForPosition(firstVisibleItem);
- int nextSecPosition = indexer.getPositionForSection(section + 1);
- if (firstVisibleItem != lastFirstVisibleItem) {
- MarginLayoutParams params = (MarginLayoutParams) titleLayout.getLayoutParams();
- params.topMargin = 0;
- titleLayout.setLayoutParams(params);
- title.setText(String.valueOf(alphabet.charAt(section)));
- }
- if (nextSecPosition == firstVisibleItem + 1) {
- View childView = view.getChildAt(0);
- if (childView != null) {
- int titleHeight = titleLayout.getHeight();
- int bottom = childView.getBottom();
- MarginLayoutParams params = (MarginLayoutParams) titleLayout
- .getLayoutParams();
- if (bottom < titleHeight) {
- float pushedDistance = bottom - titleHeight;
- params.topMargin = (int) pushedDistance;
- titleLayout.setLayoutParams(params);
- } else {
- if (params.topMargin != 0) {
- params.topMargin = 0;
- titleLayout.setLayoutParams(params);
- }
- }
- }
- }
- lastFirstVisibleItem = firstVisibleItem;
- }
- });
- }
- /**
- * 获取sort key的首个字符,如果是英文字母就直接返回,否则返回#。
- *
- * @param sortKeyString
- * 数据库中读取出的sort key
- * @return 英文字母或者#
- */
- private String getSortKey(String sortKeyString) {
- String key = sortKeyString.substring(0, 1).toUpperCase();
- if (key.matches("[A-Z]")) {
- return key;
- }
- return "#";
- }
- }
在 onCreate 中,我們從系統通訊錄資料庫撈出聯絡人的姓名與排序鍵,接著把查詢得到的 cursor 直接交給 AlphabetIndexer 作為第一個參數。由於我們只查了兩欄,排序鍵位於第二欄,所以 sortedColumnIndex 傳入 1;alphabet 參數則傳入 "#ABCDEFGHIJKLMNOPQRSTUVWXYZ",因為有些姓名可能落在英文字母之外,我們統一以 # 來歸類這部分聯絡人。
而在 setupContactsListView 裡,我們為 ListView 掛上滾動監聽。onScroll 中先透過 getSectionForPosition 取得第一個可見項的分組,將它加一後再用 getPositionForSection 換算下一個分組的首個位置。如果這個位置恰好等於「第一個可見項 + 1」,就代表下一個分組的標籤即將與頂部標籤相撞。此時用 getChildAt(0) 取出畫面上第一個子 View,以 getBottom 取得它距父容器的底部距離,再對照分組標籤的高度做縱向位移,擠壓動畫便自然浮現了。
最後附上 AndroidManifest.xml。由於要讀取聯絡人,別忘了加上 android.permission.READ_CONTACTS 權限宣告:
- <manifest xmlns:android="https://schemas.android.com/apk/res/android"
- package="com.example.contactsdemo"
- android:versionCode="1"
- android:versionName="1.0" >
- <uses-sdk
- android:minSdkVersion="8"
- android:targetSdkVersion="8" />
- <uses-permission android:name="android.permission.READ_CONTACTS"></uses-permission>
- <application
- android:allowBackup="true"
- android:icon="@drawable/ic_launcher"
- android:label="@string/app_name"
- android:theme="@android:style/Theme.NoTitleBar" >
- >
- <activity
- android:name="com.example.contactsdemo.MainActivity"
- android:label="@string/app_name" >
- <intent-filter>
- <action android:name="android.intent.action.MAIN" />
- <category android:name="android.intent.category.LAUNCHER" />
- </intent-filter>
- </activity>
- </application>
- </manifest>
一切就緒,跑起來看看成果:
至此,分組導航與擠壓動畫都已大功告成,成品頗為順眼。下一篇我會带大家繼續打磨這個程式,加入字母表快速滾動的功能,有興趣的朋友敬請期待。
源碼下載,請點擊這裡
Android 登入畫面實作:帳號驗證與錯誤次數限制
登入畫面是許多 App 的第一道門檻。基本元素包含使用者名稱、密碼與登入按鈕。密碼欄位應設定 inputType=textPassword,避免密碼以明碼顯示。 <
Android 檔案選擇器實作教學
檔案選擇器的用途 Android 檔案選擇器常用於讓使用者瀏覽 SD 卡或內部儲存空間,並選取特定檔案。它的概念類似傳統桌面平台的 OpenFileDialog,重點在於
AudioManager 實戰:用程式控制鈴聲模式與音量
想要讓 App 直接切換手機的鈴聲模式(正常、靜音、震動),Android 提供了 AudioManager 這個系統服務。本文示範如何取得它、切換模式、讀回目前狀態,並
libGDX 實作:顯示資源載入進度百分比
這個案例結構簡單,直接用 AndroidApplication → Game → Stage 三層搭建即可。 一、主入口 public class App extend