Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
您现在的位置: Android教程網 >> Android系統教程 >  >> Android 技術 >> Android 開發實例

Android 實作通訊錄字母分組導航與擠壓動畫

編輯: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 作為主布局,寫入以下程式碼:

  1. <RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android" 
  2.     xmlns:tools="https://schemas.android.com/tools" 
  3.     android:layout_width="match_parent" 
  4.     android:layout_height="match_parent" 
  5.     android:orientation="vertical" > 
  6.  
  7.     <ListView 
  8.         android:id="@+id/contacts_list_view" 
  9.         android:layout_width="fill_parent" 
  10.         android:layout_height="wrap_content" 
  11.         android:layout_alignParentTop="true" 
  12.         android:fadingEdge="none" > 
  13.     </ListView> 
  14.       
  15.      <LinearLayout 
  16.         android:id="@+id/title_layout" 
  17.         android:layout_width="fill_parent" 
  18.         android:layout_height="18dip" 
  19.         android:layout_alignParentTop="true" 
  20.         android:background="#303030" > 
  21.  
  22.         <TextView 
  23.             android:id="@+id/title" 
  24.             android:layout_width="wrap_content" 
  25.             android:layout_height="wrap_content" 
  26.             android:layout_gravity="center_horizontal" 
  27.             android:layout_marginLeft="10dip" 
  28.             android:textColor="#ffffff" 
  29.             android:textSize="13sp" /> 
  30.     </LinearLayout> 
  31.  
  32. </RelativeLayout> 

這個布局並不複雜:一個 ListView 負責呈現聯絡人清單,頂部再疊放一個 LinearLayout,內含一個 TextView,用來在介面上方常駐顯示目前的分組字母。

 

接著新建 contact_item.xml,作為 ListView 每一列的填充模板,程式碼如下:

  1. <LinearLayout xmlns:android="https://schemas.android.com/apk/res/android" 
  2.     android:layout_width="match_parent" 
  3.     android:layout_height="match_parent" 
  4.     android:orientation="vertical" > 
  5.  
  6.     <LinearLayout 
  7.         android:id="@+id/sort_key_layout" 
  8.         android:layout_width="fill_parent" 
  9.         android:layout_height="18dip" 
  10.         android:background="#303030" > 
  11.  
  12.         <TextView 
  13.             android:id="@+id/sort_key" 
  14.             android:layout_width="wrap_content" 
  15.             android:layout_height="wrap_content" 
  16.             android:layout_gravity="center_horizontal" 
  17.             android:layout_marginLeft="10dip" 
  18.             android:textColor="#ffffff" 
  19.             android:textSize="13sp" /> 
  20.     </LinearLayout> 
  21.  
  22.     <LinearLayout 
  23.         android:id="@+id/name_layout" 
  24.         android:layout_width="fill_parent" 
  25.         android:layout_height="50dip" > 
  26.  
  27.         <ImageView 
  28.             android:layout_width="wrap_content" 
  29.             android:layout_height="wrap_content" 
  30.             android:layout_gravity="center_vertical" 
  31.             android:layout_marginLeft="10dip" 
  32.             android:layout_marginRight="10dip" 
  33.             android:src="@drawable/icon" /> 
  34.  
  35.         <TextView 
  36.             android:id="@+id/name" 
  37.             android:layout_width="wrap_content" 
  38.             android:layout_height="wrap_content" 
  39.             android:layout_gravity="center_vertical" 
  40.             android:textColor="#ffffff" 
  41.             android:textSize="22sp" /> 
  42.     </LinearLayout> 
  43.  
  44. </LinearLayout> 

這個模板的設計思路很清楚:頂部同樣放一個分組標籤布局,因為除了介面上方,每個分組的第一個項目之前也需要顯示分組;下方則是一個簡單的 LinearLayout,內含顯示頭像的 ImageView 與顯示姓名的 TextView。

 

布局部分到此全部搞定,接下來才是真正的功能實作。
 

先從最簡單的 Contact 實體類開始:

  1. public class Contact {  
  2.  
  3.     /**  
  4.      * 聯系人姓名  
  5.      */ 
  6.     private String name;  
  7.  
  8.     /**  
  9.      * 排序字母  
  10.      */ 
  11.     private String sortKey;  
  12.  
  13.     public String getName() {  
  14.         return name;  
  15.     }  
  16.  
  17.     public void setName(String name) {  
  18.         this.name = name;  
  19.     }  
  20.  
  21.     public String getSortKey() {  
  22.         return sortKey;  
  23.     }  
  24.  
  25.     public void setSortKey(String sortKey) {  
  26.         this.sortKey = sortKey;  
  27.     }  
  28.  
  29. }  

這個類別只承載聯絡人姓名與排序鍵,非常輕量。
 

再來撰寫聯絡人清單的適配器。新建 ContactAdapter 類別並繼承 ArrayAdapter:

  1. public class ContactAdapter extends ArrayAdapter<Contact> {  
  2.  
  3.     /**  
  4.      * 需要渲染的item布局文件  
  5.      */ 
  6.     private int resource;  
  7.  
  8.     /**  
  9.      * 字母表分組工具  
  10.      */ 
  11.     private SectionIndexer mIndexer;  
  12.  
  13.     public ContactAdapter(Context context, int textViewResourceId, List<Contact> objects) {  
  14.         super(context, textViewResourceId, objects);  
  15.         resource = textViewResourceId;  
  16.     }  
  17.  
  18.     @Override 
  19.     public View getView(int position, View convertView, ViewGroup parent) {  
  20.         Contact contact = getItem(position);  
  21.         LinearLayout layout = null;  
  22.         if (convertView == null) {  
  23.             layout = (LinearLayout) LayoutInflater.from(getContext()).inflate(resource, null);  
  24.         } else {  
  25.             layout = (LinearLayout) convertView;  
  26.         }  
  27.         TextView name = (TextView) layout.findViewById(R.id.name);  
  28.         LinearLayout sortKeyLayout = (LinearLayout) layout.findViewById(R.id.sort_key_layout);  
  29.         TextView sortKey = (TextView) layout.findViewById(R.id.sort_key);  
  30.         name.setText(contact.getName());  
  31.         int section = mIndexer.getSectionForPosition(position);  
  32.         if (position == mIndexer.getPositionForSection(section)) {  
  33.             sortKey.setText(contact.getSortKey());  
  34.             sortKeyLayout.setVisibility(View.VISIBLE);  
  35.         } else {  
  36.             sortKeyLayout.setVisibility(View.GONE);  
  37.         }  
  38.         return layout;  
  39.     }  
  40.  
  41.     /**  
  42.      * 給當前適配器傳入一個分組工具。  
  43.      *  
  44.      * @param indexer  
  45.      */ 
  46.     public void setIndexer(SectionIndexer indexer) {  
  47.         mIndexer = indexer;  
  48.     }  
  49.  
  50. } 

這段程式碼的靈魂在 getView 方法。我們先用 getSectionForPosition 依當前 position 取得對應的 section,再用這個 section 反查 getPositionForSection 得到新的 position。若兩個 position 相等,就代表目前這項是某個分組的第一個元素,此時顯示分組標籤;否則一律隱藏。這正是分組標籤只出現在每組開頭的關鍵。

最後來寫主介面。打開或建立 MainActivity:

  1. public class MainActivity extends Activity {  
  2.  
  3.     /**  
  4.      * 分組的布局  
  5.      */ 
  6.     private LinearLayout titleLayout;  
  7.  
  8.     /**  
  9.      * 分組上顯示的字母  
  10.      */ 
  11.     private TextView title;  
  12.  
  13.     /**  
  14.      * 聯系人ListView  
  15.      */ 
  16.     private ListView contactsListView;  
  17.  
  18.     /**  
  19.      * 聯系人列表適配器  
  20.      */ 
  21.     private ContactAdapter adapter;  
  22.  
  23.     /**  
  24.      * 用于进行字母表分组  
  25.      */ 
  26.     private AlphabetIndexer indexer;  
  27.  
  28.     /**  
  29.      * 存儲所有手機中的聯系人  
  30.      */ 
  31.     private List<Contact> contacts = new ArrayList<Contact>();  
  32.  
  33.     /**  
  34.      * 定義字母表的排序規則  
  35.      */ 
  36.     private String alphabet = "#ABCDEFGHIJKLMNOPQRSTUVWXYZ";  
  37.  
  38.     /**  
  39.      * 上次第一個可見元素,用于滚动时记录标识。  
  40.      */ 
  41.     private int lastFirstVisibleItem = -1;  
  42.  
  43.     @Override 
  44.     protected void onCreate(Bundle savedInstanceState) {  
  45.         super.onCreate(savedInstanceState);  
  46.         setContentView(R.layout.activity_main);  
  47.         adapter = new ContactAdapter(this, R.layout.contact_item, contacts);  
  48.         titleLayout = (LinearLayout) findViewById(R.id.title_layout);  
  49.         title = (TextView) findViewById(R.id.title);  
  50.         contactsListView = (ListView) findViewById(R.id.contacts_list_view);  
  51.         Uri uri = ContactsContract.CommonDataKinds.Phone.CONTENT_URI;  
  52.         Cursor cursor = getContentResolver().query(uri,  
  53.                 new String[] { "display_name", "sort_key" }, null, null, "sort_key");  
  54.         if (cursor.moveToFirst()) {  
  55.             do {  
  56.                 String name = cursor.getString(0);  
  57.                 String sortKey = getSortKey(cursor.getString(1));  
  58.                 Contact contact = new Contact();  
  59.                 contact.setName(name);  
  60.                 contact.setSortKey(sortKey);  
  61.                 contacts.add(contact);  
  62.             } while (cursor.moveToNext());  
  63.         }  
  64.         startManagingCursor(cursor);  
  65.         indexer = new AlphabetIndexer(cursor, 1, alphabet);  
  66.         adapter.setIndexer(indexer);  
  67.         if (contacts.size() > 0) {  
  68.             setupContactsListView();  
  69.         }  
  70.     }  
  71.  
  72.     /**  
  73.      * 为联系人ListView设置监听事件,根据当前的滑动状态来改变分组的显示位置,从而实现挤压动画的效果。  
  74.      */ 
  75.     private void setupContactsListView() {  
  76.         contactsListView.setAdapter(adapter);  
  77.         contactsListView.setOnScrollListener(new OnScrollListener() {  
  78.             @Override 
  79.             public void onScrollStateChanged(AbsListView view, int scrollState) {  
  80.             }  
  81.  
  82.             @Override 
  83.             public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, 
  84.                      int totalItemCount) {  
  85.                      int section = indexer.getSectionForPosition(firstVisibleItem);  
  86.                      int nextSecPosition = indexer.getPositionForSection(section + 1);  
  87.                      if (firstVisibleItem != lastFirstVisibleItem) {  
  88.                          MarginLayoutParams params = (MarginLayoutParams) titleLayout.getLayoutParams();  
  89.                          params.topMargin = 0;  
  90.                          titleLayout.setLayoutParams(params);  
  91.                          title.setText(String.valueOf(alphabet.charAt(section)));  
  92.                      }  
  93.                      if (nextSecPosition == firstVisibleItem + 1) {  
  94.                          View childView = view.getChildAt(0);  
  95.                          if (childView != null) {  
  96.                              int titleHeight = titleLayout.getHeight();  
  97.                              int bottom = childView.getBottom();  
  98.                              MarginLayoutParams params = (MarginLayoutParams) titleLayout  
  99.                                 .getLayoutParams();  
  100.                              if (bottom < titleHeight) {  
  101.                                 float pushedDistance = bottom - titleHeight;  
  102.                                 params.topMargin = (int) pushedDistance;  
  103.                                 titleLayout.setLayoutParams(params);  
  104.                              } else {  
  105.                                 if (params.topMargin != 0) {  
  106.                                     params.topMargin = 0;  
  107.                                     titleLayout.setLayoutParams(params);  
  108.                                 }  
  109.                              }  
  110.                          }  
  111.                      }  
  112.                      lastFirstVisibleItem = firstVisibleItem;  
  113.                 }  
  114.             });  
  115.  
  116.     }  
  117.  
  118.     /**  
  119.      * 获取sort key的首个字符,如果是英文字母就直接返回,否则返回#。  
  120.      *  
  121.      * @param sortKeyString  
  122.      *             数据库中读取出的sort key  
  123.      * @return 英文字母或者#  
  124.      */ 
  125.     private String getSortKey(String sortKeyString) {  
  126.         String key = sortKeyString.substring(0, 1).toUpperCase();  
  127.         if (key.matches("[A-Z]")) {  
  128.             return key;  
  129.         }  
  130.         return "#";  
  131.     }  
  132.  
  133. } 

在 onCreate 中,我們從系統通訊錄資料庫撈出聯絡人的姓名與排序鍵,接著把查詢得到的 cursor 直接交給 AlphabetIndexer 作為第一個參數。由於我們只查了兩欄,排序鍵位於第二欄,所以 sortedColumnIndex 傳入 1;alphabet 參數則傳入 "#ABCDEFGHIJKLMNOPQRSTUVWXYZ",因為有些姓名可能落在英文字母之外,我們統一以 # 來歸類這部分聯絡人。

而在 setupContactsListView 裡,我們為 ListView 掛上滾動監聽。onScroll 中先透過 getSectionForPosition 取得第一個可見項的分組,將它加一後再用 getPositionForSection 換算下一個分組的首個位置。如果這個位置恰好等於「第一個可見項 + 1」,就代表下一個分組的標籤即將與頂部標籤相撞。此時用 getChildAt(0) 取出畫面上第一個子 View,以 getBottom 取得它距父容器的底部距離,再對照分組標籤的高度做縱向位移,擠壓動畫便自然浮現了。

 

最後附上 AndroidManifest.xml。由於要讀取聯絡人,別忘了加上 android.permission.READ_CONTACTS 權限宣告:

  1. <manifest xmlns:android="https://schemas.android.com/apk/res/android" 
  2.     package="com.example.contactsdemo" 
  3.     android:versionCode="1" 
  4.     android:versionName="1.0" > 
  5.  
  6.     <uses-sdk 
  7.         android:minSdkVersion="8" 
  8.         android:targetSdkVersion="8" /> 
  9.       
  10.     <uses-permission android:name="android.permission.READ_CONTACTS"></uses-permission> 
  11.  
  12.     <application 
  13.         android:allowBackup="true" 
  14.         android:icon="@drawable/ic_launcher" 
  15.         android:label="@string/app_name" 
  16.         android:theme="@android:style/Theme.NoTitleBar" > 
  17.         > 
  18.         <activity 
  19.             android:name="com.example.contactsdemo.MainActivity" 
  20.             android:label="@string/app_name" > 
  21.             <intent-filter> 
  22.                 <action android:name="android.intent.action.MAIN" /> 
  23.  
  24.                 <category android:name="android.intent.category.LAUNCHER" /> 
  25.             </intent-filter> 
  26.         </activity> 
  27.     </application> 
  28.  
  29. </manifest> 

一切就緒,跑起來看看成果:

                                             

至此,分組導航與擠壓動畫都已大功告成,成品頗為順眼。下一篇我會带大家繼續打磨這個程式,加入字母表快速滾動的功能,有興趣的朋友敬請期待。

源碼下載,請點擊這裡

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