常見Adapter

本文來自

檸檬的博客

http://blog.sina.com.cn/demonzym


從google的demo開始,第一個NoteList開始就出現了Adapter、List,而觀察常見的一些android應用,跟adapter相關的界面也經常出現,所以覺得,不好好學習一下,以後是會帶來諸多麻煩的。
   Adapter在Android開發中佔據着非常重要的地位,它是data和ui之間的一個關鍵,如圖所示
Android常用Adapter的學習總結
      這個圖片來自GoogleI/O,非常形象的表明了adapter在程序中扮演什麼樣的角色。
   
   先看下Adapter的層次。 
   Android常用Adapter的學習總結

一、 Adapter是在android.widget中的一個頂層接口,下面有諸多不同的Adapter實現這個接口來達到不同的目的。
   ListAdapter綁定了Data和ListView。SpinnerAdapter綁定了Data和Spinner,兩個都是接口,需要實現。這兩者以後的實現類,使用方法都是一樣的,只是在綁定不同類型的view時顯示的效果不同罷了。

其中最常用的有BaseAdapter,SimpleCursorAdapter和ArrayAdapter。
   
上圖可以看到 BaseAdapter是抽象類
Android常用Adapter的學習總結所以需要實現好多的抽象方法,當然,也說明可控制性最強,可以自定義很多需要的東西。

二、SimpleCursorAdapter,可以用於純文字的ListView,它必須使Cursor的字段和UI的界面元素id對應起來。非常的適合於數據庫的數據提取,所以被廣泛用於各種數據庫相關界面。Android常用Adapter的學習總結
public class simpleCursorAdapter extendsSimpleCursorAdapter{

public simpleCursorAdapter(Context context, int layout, Cursorc,
String[] from, int[] to) {
super(context, layout, c, from, to);
// TODO Auto-generated constructor stub
}
}

繼承自SimpleCursorAdapter以後,要實現其構造函數,幫助文檔是這樣描述的
context     The contextwhere the ListView associated with this SimpleListItemFactory isrunning
layout      resourceidentifier of a layout file that defines the views for this listitem. The layout file should include at least those named viewsdefined in "to"
c         The database cursor. Can be null if thecursor is not available yet.
from       A list of column names representing thedata to bind to the UI. Can be null if the cursor is not availableyet.
to         The views thatshould display column in the "from" parameter. These should all beTextViews. The first N views in this list are given the values ofthe first N columns in the from parameter. Can be null if thecursor is not available yet.

context   與其關聯的上下文
layout   listview或者spinnerview所在的layout
c        cursor
from     列名稱所組成的string數組
to      與列名稱,即數組元素所對應的界面元素,from與to要一一對應,不然結果無法正確顯示

當然,SimpleCursorAdapter的列表界面也可以自定義。

三、ArrayAdapter
支持泛型操作Android常用Adapter的學習總結

通常會需要實現getView方法,特殊情況下(結合數據的rowid),爲了讓ui時間相應處理方便點,最好重寫getItemId。



有一個比較特殊的:

HeaderViewListAdapter

Adapter的層次圖中可以看到,它implements Filterable WrapperListAdapter

ListAdapterused when a ListView has header views. This ListAdapter wrapsanother one and also keeps track of the header views and theirassociated data objects.This is intended as a base class; you willprobably not need to use this class directly in your owncode.

即對list首行的特殊化處理。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章