本文轉自:http://www.cnblogs.com/allin/archive/2010/05/11/1732200.html
如欲獲得更多更好的信息,請訪問原文地址,這裏僅作記載
SimpleAdapter
simpleAdapter的擴展性最好,可以定義各種各樣的佈局出來,可以放上ImageView(圖片),還可以放上Button(按鈕),CheckBox(複選框)等等。下面的代碼都直接繼承了ListActivity,ListActivity和普通的Activity沒有太大的差別,不同就是對顯示ListView做了許多優化,方面顯示而已。
下面的程序是實現一個帶有圖片的類表。
首先需要定義好一個用來顯示每一個列內容的xml
vlist.xml
01 |
<? xml version = "1.0" encoding = "utf-8" ?> |
03 |
android:orientation = "horizontal" android:layout_width = "fill_parent" |
04 |
android:layout_height = "fill_parent" > |
07 |
< ImageView android:id = "@+id/img" |
08 |
android:layout_width = "wrap_content" |
09 |
android:layout_height = "wrap_content" |
10 |
android:layout_margin = "5px" /> |
12 |
< LinearLayout android:orientation = "vertical" |
13 |
android:layout_width = "wrap_content" |
14 |
android:layout_height = "wrap_content" > |
16 |
< TextView android:id = "@+id/title" |
17 |
android:layout_width = "wrap_content" |
18 |
android:layout_height = "wrap_content" |
19 |
android:textColor = "#FFFFFFFF" |
20 |
android:textSize = "22px" /> |
21 |
< TextView android:id = "@+id/info" |
22 |
android:layout_width = "wrap_content" |
23 |
android:layout_height = "wrap_content" |
24 |
android:textColor = "#FFFFFFFF" |
25 |
android:textSize = "13px" /> |
下面是實現代碼:
05 |
public class MyListView3 extends ListActivity
{ |
10 |
public void onCreate(Bundle
savedInstanceState) { |
11 |
super .onCreate(savedInstanceState); |
13 |
SimpleAdapter
adapter = new SimpleAdapter( this ,getData(),R.layout.vlist, |
14 |
new String[]{ "title" , "info" , "img" }, |
15 |
new int []{R.id.title,R.id.info,R.id.img}); |
16 |
setListAdapter(adapter); |
19 |
private List<Map<String,
Object>> getData() { |
20 |
List<Map<String,
Object>> list = new ArrayList<Map<String,
Object>>(); |
22 |
Map<String,
Object> map = new HashMap<String,
Object>(); |
23 |
map.put( "title" , "G1" ); |
24 |
map.put( "info" , "google
1" ); |
25 |
map.put( "img" ,
R.drawable.i1); |
28 |
map
= new HashMap<String,
Object>(); |
29 |
map.put( "title" , "G2" ); |
30 |
map.put( "info" , "google
2" ); |
31 |
map.put( "img" ,
R.drawable.i2); |
34 |
map
= new HashMap<String,
Object>(); |
35 |
map.put( "title" , "G3" ); |
36 |
map.put( "info" , "google
3" ); |
37 |
map.put( "img" ,
R.drawable.i3); |
使用simpleAdapter的數據用一般都是HashMap構成的List,list的每一節對應ListView的每一行。HashMap的每個鍵值數據映射到佈局文件中對應id的組件上。因爲系統沒有對應的佈局文件可用,我們可以自己定義一個佈局vlist.xml。下面做適配,new一個SimpleAdapter參數一次是:this,佈局文件(vlist.xml),HashMap的 title 和 info,img。佈局文件的組件id,title,info,img。佈局文件的各組件分別映射到HashMap的各元素上,完成適配。
運行效果如下圖:
![]()