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

Android 音樂播放器源碼分析(二):BaseExpandableListAdapter 與 SimpleCursorTreeAdapter

編輯:Android 開發實例

一、SimpleExpandableListAdapter 與 BaseExpandableListAdapter

這兩個類別的建構子會一次接收多個參數,核心呼叫形式如下:

this(context, groupData, expandedGroupLayout, collapsedGroupLayout, groupFrom, groupTo, childData, childLayout, lastChildLayout, childFrom, childTo);

實務上,expandedGroupLayout 與 collapsedGroupLayout 往往由同一個參數產生,childLayout 與 lastChildLayout 亦然。之所以要區分,是因為存在兩種需求:一是要在展開與收合等不同狀態下呈現不同的 view;二是要為「每個群組的最後一個子節點」單獨指定布局。

使用 BaseExpandableListAdapter 時,若採用類似 newGroupView 的寫法:

public View newGroupView(boolean isExpanded, ViewGroup parent) {
    return mInflater.inflate((isExpanded) ? mExpandedGroupLayout : mCollapsedGroupLayout, parent, false);
}

在綁定內容時,有幾個重點必須留意:

  1. 綁定的內容一定要與 groupPosition 相對應,且最好不要動態產生,否則會造成綁定不穩定。若要綁定子節點內容,就必須與 groupPosition、childPosition 一一對應;而且每次呼叫都需要重新綁定一次,不能僅憑 convertView 來判斷是否重用(convertView 是 getChildView 等方法的參數)。
  2. 覆寫 getChild 方法時,應回傳自己所需的資料結構,可依情況自訂合適的型別。
  3. mInflater.inflate 在實例化某個 layout 時,可能會一併建立其他 group 的 layout(這部分成因尚待釐清);相比之下,若改用 TextView textView = new TextView(Class.this) 就不會有這個問題,每次綁定時 convertView 一定是空的。

二、SimpleCursorTreeAdapter 與 ResourceCursorTreeAdapter

這類別接受一個 cursor 作為參數,而在 musicplayer 的實作中則是傳入 null,改由內部的 AsyncQueryHandler 來產生 cursor。整體流程如下:

  1. 首先在適配器中建立 AsyncQueryHandler,此時 cursor 為空。
  2. 於主程式呼叫適配器的 AsyncQueryHandler 執行 SQL 查詢,並在覆寫的 onQueryComplete 等回呼方法中,把產生的 cursor 交給適配器。
@Override
protected void onQueryComplete(int token, Object cookie, Cursor cursor) {
    if (cursor != null) {
        cursor = mActivity.mergedCursor(cursor);
    }
    mActivity.init(cursor);
}
  1. 接著由適配器自動呼叫 get 與 bind 方法來產生布局。綁定內容時要特別注意:由於使用了 cursor,無法自行決定 group 與 child 的數量,其大小完全由 cursor 決定。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved