上一節中一些列表集合數據到手機屏幕時,一般採用ListView組件+ArrayAdapter. android
雖然它能爲咱們提供展現數據列表的能力,可是展現的項卻不能定製,若是咱們的項是由2個TextView組成的,它就無能爲力了。項目中大部分的不僅僅是展現簡單的項模板,更多時候,咱們能夠對項模板進行一些定製,來知足咱們的需求,假設項模板須要展現2個TextView 呢?怎麼辦?web
咱們能夠使用SimpleAdapter+ListView來實現。函數
SimpleAdapter其中一個構造函數以下:佈局
public SimpleAdapter (Context context, List<? extends Map<String, ?>> data, int resource, String[] from, int[] to)
第一個參數:當前上下文對象。第二個參數:一個List類型的泛型集合,泛型類型必須繼承之Map類型。第三個:佈局資源的ID,this
第四個參數:須要綁定的Key列表。第五個參數:與Key列表項對應的資源文件中的具體組件ID集合。spa
有以上的理論基礎,咱們知道使用SimpleAdapter會帶來這樣的好處:code
1:能夠自定義任何項模板,自由度很高(取決於美工水平)orm
2:能夠爲項模板指定一個匹配的數據xml
咱們先來看看項模板的佈局,很簡單,就是一個ImageView,兩個TextView對象
<? xml version="1.0" encoding="utf-8" ?> <LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"android:layout_width="match_parent" android:layout_height ="match_parent" > < ImageView
android:layout_width ="wrap_content"
android:layout_height ="wrap_content"
android:id ="@+id/img" >
</ ImageView >
< TextView
android:id ="@+id/txtName"
android:layout_width ="wrap_content"
android:layout_height ="wrap_content"
>
</ TextView >
< TextView
android:paddingLeft ="20sp"
android:id ="@+id/txtLength"
android:layout_width ="wrap_content"
android:layout_height ="wrap_content"
>
</ TextView >
</ LinearLayout >
咱們能夠定義數據源,固然這個數據源是繼承自List集合接口的,而且類型爲基礎Map接口。以下:
List < Map < String,Object >> lists = new ArrayList < Map < String,Object >> ();
for ( int i = 0 ;i < 4 ;i ++ ){
Map < String,Object > map = new HashMap < String,Object > ();
map.put( " img " , R.drawable.icon);
map.put( " name " , " SimpleAdapter " + i);
map.put( " length " , " 300 " );
lists.add(map);
}
而後咱們但願綁定這些數據,到指定的組件中去,所有代碼以下:
List < Map < String,Object >> lists = new ArrayList < Map < String,Object >> ();
for ( int i = 0 ;i < 4 ;i ++ ){
Map < String,Object > map = new HashMap < String,Object > ();
map.put( " img " , R.drawable.icon);
map.put( " name " , " SimpleAdapter " + i);
map.put( " length " , " 300 " );
lists.add(map);
}
String []from = { " img " , " name " , " length " };
int []to = {R.id.img,R.id.txtName,R.id.txtLength};
SimpleAdapter adapter = new SimpleAdapter( this ,lists, R.layout.image, from, to);
listView.setAdapter(adapter);
看看運行截圖吧: