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

讀取 Android 聯絡人並依字母分組展示(二)

編輯:關於 Android 程式設計

目標:讓相同首字母的聯絡人歸在同一組

上一篇我們把聯絡人讀了出來、排好了序,但清單還是一整片到底。這一階段要做的,是在滑動時讓右側出現字母索引,並在切換分組的位置插入分類標題——也就是 iOS 通訊錄那種熟悉的手感。

關鍵:實作 SectionIndexer

Adapter 只要實作 SectionIndexer 介面,ListView 就會自動把快速滑動的索引條接上來。這個介面要求三個方法:

@Override
public Object[] getSections() {
    // section 的集合
}

@Override
public int getPositionForSection(int section) {
    // 目前 section 對應的 position
}

@Override
public int getSectionForPosition(int position) {
    // 目前 position 所屬的 section
}

問題是:這三個方法要回傳的資訊,Cursor 本身並不提供。所以我們必須先對查回來的原始資料做一層加工,把「第幾個位置」與「屬於哪一組」的對應關係預先算出來。

定義 section 的資料結構

private class SectionTitle {
    public String title;

    public SectionTitle() {
        title = "";
    }

    public String toString() {
        return title;
    }
}

封裝 SectionIndexer 的實作

把三個介面方法與對應表包成一個獨立的 mapper,Adapter 本體就不必被這些細節污染:

private class ContactSectionMapper implements SectionIndexer {

    private SectionTitle[] mSections = null;
    private SparseIntArray mSectionPositionMap = null;   // section -> position
    private SparseIntArray mPositionSectionMap = null;   // position -> section

    public ContactSectionMapper(SectionTitle[] sectionDatas) {
        mSections = sectionDatas;
    }

    public void changeData(SparseIntArray sectionPositionMap,
                           SparseIntArray positionSectionMap) {
        mSectionPositionMap = sectionPositionMap;
        mPositionSectionMap = positionSectionMap;
    }

    @Override
    public Object[] getSections() {
        return mSections;
    }

    /** 找出這個 section 對應的 position */
    @Override
    public int getPositionForSection(int section) {
        if (mSectionPositionMap == null) return -1;
        if (section == 0) return -1;
        return mSectionPositionMap.get(section, -1);
    }

    /** 找出這個 position 對應的 section */
    @Override
    public int getSectionForPosition(int position) {
        if (mPositionSectionMap == null) return -1;
        if (position <= 0) return 0;
        return mPositionSectionMap.get(position, -1);
    }

    /** 判斷某個 position 是否為 section 的起始位置 */
    public boolean isSection(int position) {
        if (position == 0) return true;
        int sectionIdx = getSectionForPosition(position);
        int sectionPosition = getPositionForSection(sectionIdx);
        if (sectionIdx == -1 && sectionPosition == -1) return false;
        return (position == sectionPosition);
    }

    public String getSection(int position) {
        if (mSections == null) return NONE_ENGLISH_LETTER_TITLE;
        int sectionIndex = getSectionForPosition(position);
        if (sectionIndex < 0 || sectionIndex >= mSections.length)
            return NONE_ENGLISH_LETTER_TITLE;
        return mSections[sectionIndex].toString();
    }
}

這裡用 SparseIntArray 而不是 HashMap,是因為 key 與 value 都是整數,SparseIntArray 內部以陣列儲存、省下每筆 entry 的物件 Boxing 開銷。在這種一次要建幾百筆對應表的場景,差異相當可觀。

在 changeCursor 中加工資料

每次 Cursor 改變(查詢完成、資料更新)都會經過這裡,正好是我們重建對應表的時機:

@Override
public void changeCursor(Cursor c) {
    processCursor(c);
    super.changeCursor(c);
}

private void processCursor(Cursor c) {
    SparseIntArray sectionPositionMap = new SparseIntArray();
    SparseIntArray positionSectionMap = new SparseIntArray();

    for (int i = 0; i < mSectionDatas.length; i++) {
        mSectionDatas[i].title = "";
    }

    if (c == null || c.getCount() == 0 || c.isClosed()) {
        mSectionMapper.changeData(sectionPositionMap, positionSectionMap);
        return;
    }

    String curtitle = "";
    int i = 0;
    int position = 0;

    while (c.moveToNext()) {
        position = c.getPosition();
        // 看看目前這個名字的第一個字母是什麼,是不是某個 section 的開頭
        String curLetter = getTitle(getDisplayName(c));

        if (TextUtils.isEmpty(curtitle) || !TextUtils.equals(curLetter, curtitle)) {
            mSectionDatas[i].title = curLetter;   // 這個名字就是一個新 section 的開頭
            sectionPositionMap.put(i, position);
            curtitle = curLetter;
            i++;
        }
        positionSectionMap.put(position, i - 1);
    }

    // 剩下的 section 沒有對應資料,補上汽空標題與末位 position
    for (; i < mSectionDatas.length; i++) {
        mSectionDatas[i].title = curtitle;
        sectionPositionMap.put(i, position);
    }

    mSectionMapper.changeData(sectionPositionMap, positionSectionMap);
}

演算法很直白:逐列掃過 Cursor,拿當前聯絡人的首字母與「上一個記錄下的標題」比對。不同就代表遇到新分組的開頭,此時在 sectionPositionMap 記一笔「第 i 組從 position 開始」,同時在 positionSectionMap 記下每一列屬於第幾組。兩張表方向相反,分別服務 getPositionForSection() 與 getSectionForPosition()。

前提是資料必須已按首字母排序——這正是上一篇那個 CASE WHEN ... COLLATE LOCALIZED 排序子句的作用。若排序錯了,同一字母會被切成好幾段,索引條就會出現重複項目。

Adapter 初始化

protected final class ContactsAdapter extends ResourceCursorAdapter
        implements SectionIndexer, OnScrollListener {

    protected boolean mLoading = true;

    private ContactSectionMapper mSectionMapper = null;
    private SectionTitle[] mSectionDatas = null;

    private static final int SECTION_COUNT = 27;   // A–Z 共 26 個,再加一組「其他」

    public ContactsAdapter(Context context) {
        super(context, R.layout.contacts_list_item_photo, null);

        mSectionDatas = new SectionTitle[SECTION_COUNT];
        for (int i = 0; i < SECTION_COUNT; i++) {
            mSectionDatas[i] = new SectionTitle();
        }
        mSectionMapper = new ContactSectionMapper(mSectionDatas);
    }

    @Override
    public Object[] getSections() {
        return mSectionMapper.getSections();
    }

    @Override
    public int getPositionForSection(int section) {
        return mSectionMapper.getPositionForSection(section);
    }

    @Override
    public int getSectionForPosition(int position) {
        return mSectionMapper.getSectionForPosition(position);
    }
}

固定 27 格(26 個英文字母 + 1 個非英文群組)是一個實用但略嫌僵硬的設計:索引條永遠有 27 個位置,即使某些字母下沒有任何聯絡人。若在意這點,可以改成動態長度——只為實際出現的字母建立 section,代價是 getSections() 回傳的陣列長度需與 sectionPositionMap 的 key 保持一致。

在清單項上畫出分類標題

有了 isSection(position) 這個判斷,就能在 getView() 裡決定要不要顯示標題列:

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    // ... 既有的 ViewHolder 邏輯 ...

    if (mSectionMapper.isSection(position)) {
        cache.sectionHeader.setVisibility(View.VISIBLE);
        cache.sectionHeader.setText(mSectionMapper.getSection(position));
    } else {
        cache.sectionHeader.setVisibility(View.GONE);
    }
    return convertView;
}

成果

滑到哪裡,右側索引條就對應到哪個字母;點字母可以直接跳段;分類標題會在每組開頭準時出現。這三件事湊起來,一個聯絡人清單才算真正「好用」。

小結與提醒

整套機制的骨架其實只有一句話:預先算出 position 與 section 的雙向對應表,剩下的交給 ListView 與 SectionIndexer。 需要留意的細節有三個:資料必須已排序,否則分組會重複;Cursor 為空時要記得清空對應表,不然會殘留上次的索引;SECTION_COUNT 這種魔法數字最好抽成常數並註明由來。

最後補一個現代觀點:若你在新專案實作類似需求,RecyclerView 本身並不內建 SectionIndexer,但搭配 ConcatAdapter、或直接用 ItemDecoration 畫標題、再自行接上 CustomTabLayout 這類索引元件,都能做出更好的效果與效能。本文的做法在維護舊專案時依然完全適用。

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