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

Android 3.1 API 中文解析(121):ResourceCursorTreeAdapter

編輯:Android 開發實例

本篇整理 android.widget.ResourceCursorTreeAdapter,對應版本為 Android 3.1 r1,此 API 自 Android 3.0 r1 起加入。

類別繼承關係

public abstract class ResourceCursorTreeAdapter extends CursorTreeAdapter

繼承鏈如下:

java.lang.Object
  └─ android.widget.BaseExpandableListAdapter
       └─ android.widget.CursorTreeAdapter
            └─ android.widget.ResourceCursorTreeAdapter

已知的直接子類:SimpleCursorTreeAdapter。

類別概述

這是一個簡化版的 ExpandableListAdapter。它讓你把每一種 row 的外觀交給 XML 版面配置檔來定義,而不必在程式碼裡用 newView/bindView 手工組出 View。換句話說,它把「資料綁定」這件事簡化成「指定幾個 layout 資源 id」。

建構子

最完整的版本

public ResourceCursorTreeAdapter(Context context, Cursor cursor,
        int collapsedGroupLayout, int expandedGroupLayout,
        int childLayout, int lastChildLayout)

參數說明:

  • context:與執行中的 SimpleListItemFactory 相關的 ListView 上下文。
  • cursor:資料庫游標。
  • collapsedGroupLayout:收合狀態的群組所使用的版面配置資源 id。
  • expandedGroupLayout:展開狀態的群組所使用的版面配置資源 id。
  • childLayout:除了最後一項之外,所有子項共用的版面配置資源 id。
  • lastChildLayout:每個群組中最後一個子項專用的版面配置資源 id。

省略 lastChildLayout

public ResourceCursorTreeAdapter(Context context, Cursor cursor,
        int collapsedGroupLayout, int expandedGroupLayout, int childLayout)

當你不需要為「最後一個子項」單獨設計樣式(例如不必另外畫分隔線或圓角)時,用這個版本即可,最後一項會沿用 childLayout。

最精簡的版本

public ResourceCursorTreeAdapter(Context context, Cursor cursor,
        int groupLayout, int childLayout)

只有兩個 layout:一個給所有群組、一個給所有子項,收合與展開共用同一個群組版面配置。參數中 context 一樣是 ListView 的上下文,cursor 是資料庫游標,groupLayout 為群組版面配置資源 id,childLayout 為子項版面配置資源 id。

抽象方法(由子類實作)

newChildView

protected abstract View newChildView(Context context, Cursor cursor,
        boolean isLastChild, ViewGroup parent)

建立一個新的子項 View,並把游標定位在該子項對應的資料列上。

  • context:應用程式的上下文物件。
  • cursor:已取得資料的游標,呼叫時已經移動到正確的位置。
  • isLastChild:這個子項是否為群組中的最後一項。
  • parent:新 View 要掛上去的父容器。
  • 回傳值:新建立的 View。

newGroupView

protected abstract View newGroupView(Context context, Cursor cursor,
        boolean isExpanded, ViewGroup parent)

建立一個新的群組 View,並把游標定位在該群組對應的資料列上。

  • context:應用程式的上下文物件。
  • cursor:已取得資料的游標,呼叫時已經移動到正確的位置。
  • isExpanded:這個群組目前是否處於展開狀態。
  • parent:新 View 要掛上去的父容器。
  • 回傳值:新建立的 View。

實務提醒

雖然這兩個方法被宣告為 abstract,但如果你只是要「把 XML 指定的 layout 塞進去、再把 cursor 的欄位綁到 View 上」,通常不需要自己實作——直接繼承 SimpleCursorTreeAdapter 並在建構子裡告訴它哪些欄位對應哪些 view id 就好。ResourceCursorTreeAdapter 的價值在於當版面配置需要依狀態(收合/展開、是否為最後一項)而變化時,你有一個可以覆寫的切入點。

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