adapter是android中一個重要的內容,很多的控制項都要用到它來作為資料來源。本程式使用了一個simpleAdapter作為listView的資料來源。
布局檔案裡包括一個listView和顯示在listView中的ImageView和textView。
<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"android:orientation="vertical"android:layout_width="fill_parent"android:layout_height="fill_parent"><!-- 定義一個List --><ListView android:id="@+id/mylist"android:layout_width="fill_parent"android:layout_height="wrap_content"/><!-- 定義一個ImageView,用於作為清單項目的一部分。 --><ImageView android:id="@+id/header"android:layout_width="wrap_content"android:layout_height="wrap_content" android:paddingLeft="10dp"/><!-- 定義一個TextView,用於作為清單項目的一部分。 --><TextView android:id="@+id/name"android:layout_width="wrap_content" android:layout_height="wrap_content"android:textSize="16dp"android:gravity="center_vertical"android:paddingLeft="10dp"/></LinearLayout>
用list、ImageVIew和textView來構造simpleAdapter。
public class SimpleAdapterTest extends Activity{private String[] names = new String[]{ "風箏", "完美的一天", "是時候", "stefanie"};private int[] imageIds = new int[]{ R.drawable.sunyz_1 , R.drawable.sunyz_6, R.drawable.sunyz_7 , R.drawable.sunyz_8};@Overridepublic void onCreate(Bundle savedInstanceState){super.onCreate(savedInstanceState);setContentView(R.layout.main);//建立一個List集合,List集合的元素是MapList<Map<String, Object>> listItems = new ArrayList<Map<String, Object>>();for (int i = 0; i < names.length; i++){Map<String, Object> listItem = new HashMap<String, Object>();listItem.put("CDs", imageIds[i]);listItem.put("CDname", names[i]);listItems.add(listItem);}//建立一個SimpleAdapterSimpleAdapter simpleAdapter = new SimpleAdapter(this, listItems , R.layout.main, new String[]{ "CDname", "CDs" }, new int[]{R.id.name , R.id.header});ListView list = (ListView)findViewById(R.id.mylist);//為ListView設定Adapterlist.setAdapter(simpleAdapter);}}