2011-12-18 64 views
6

我一直在玩名單活動教程這裏:自定義列表項的ListView的Android

http://developer.android.com/resources/tutorials/views/hello-listview.html

它告訴你,開始擴展列表活動。

by public class Main extends ListActivity { 

這是基於膨脹textview唯一佈局。

<?xml version="1.0" encoding="utf-8"?> 
<TextView xmlns:android="http://schemas.android.com/apk/res/android" 
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent" 
    android:padding="10dp" 
    android:textSize="16sp" > 
</TextView> 

如果我想將圖像添加到自定義佈局多了,上面的列表適配器額外的線性佈局etc-是有可能使用這種方法 - 如果是的話我該怎麼辦呢?

回答

15

可以通過使用SimpleAdapter

下面是一個例子:

// Create the item mapping 
    String[] from = new String[] { "title", "description" }; 
    int[] to = new int[] { R.id.title, R.id.description }; 

現在 「標題」 被映射到R.id.title,和 「描述」,以R.id.description(在下面的XML定義)。

// Add some rows 
    List<HashMap<String, Object>> fillMaps = new ArrayList<HashMap<String, Object>>(); 

    HashMap<String, Object> map = new HashMap<String, Object>(); 
    map.put("title", "First title"); // This will be shown in R.id.title 
    map.put("description", "description 1"); // And this in R.id.description 
    fillMaps.add(map); 

    map = new HashMap<String, Object>(); 
    map.put("title", "Second title"); 
    map.put("description", "description 2"); 
    fillMaps.add(map); 

    SimpleAdapter adapter = new SimpleAdapter(this, fillMaps, R.layout.row, from, to); 
    setListAdapter(adapter); 

這是相應的XML佈局,這裏命名row.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:orientation="vertical"> 
    <TextView 
     android:id="@+id/title" 
     android:layout_width="fill_parent" 
     android:layout_height="wrap_content" 
     android:textAppearance="?android:attr/textAppearanceMedium" /> 
    <TextView 
     android:id="@+id/description" 
     android:layout_width="fill_parent" 
     android:layout_height="wrap_content" 
     android:textAppearance="?android:attr/textAppearanceSmall" /> 
</LinearLayout> 

我用了兩個TextViews但它適用於任何一種觀點是相同的。