|  | 
 
 | 許多mobile程式中,常常會看到排列整齊的選單,有可能是接收RSS或WebService之後的列表,或是提供使用者選擇所需項目,而這類方便的介面許多時候更是貫串整個APP的重要功臣,例如我們常常會打開的設定列表等等。 
   在Android當中,要做出列表般的效果,都會藉由android.widget.Adapter的相關子類別來實現,而在很多的應用當中,其中有一種"單純只想把一類項目列出來",這時可以利用ArrayAdapter達成。
 
 整個事情要完成只有3個步驟:
 1. 在layout裡面放一個ListView。
 
 
 複製代碼<ListView    android:id="@+id/listview1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>
 2. 將ListView實體化
 
 
 複製代碼ListView Olalist = (ListView) this.findViewById(R.id.listview1); 
 3. 於要放置列表的事件中執行setAdapter。
 
 String[] item = new String[] {"Ola的家", "魔獸世界","星海爭霸2","凱蘭迪亞傳奇","Ola Query簡介","蟲族秒滅心法","Ola MapGuide教學","Ola jQuery教學","Ola Android教學"};
 ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_expandable_list_item_1,item);
 Olalist.setAdapter(adapter);
 
 上方程式碼有兩個重點:
 A. ArrayAdapte所接收之項目為Array,之所以前面說「"單純只想把一類項目列出來"」的原因也在這裡,ArrayAdapte的方法裡面並沒有提供多欄位的顯示方式。
 B. 在第二個參數中使用"android.R.layout.simple_expandable_list_item_1",表示是用Android內建的配置。
 執行結果:
 
   
 單一項目是屬於ArrayAdapte的限制,但去看ArrayAdapter的說明,可以發現他也可以使用我們自己定義的配置檔;若是使用自己的配置檔(layout),那麼就必須去指定要擺放文字的textViewResourceId。
 自訂的Layout:
 
 
 複製代碼<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
 android:orientation="horizontal"
 android:layout_width="fill_parent"
 android:layout_height="fill_parent"
 >
   <ImageView
       android:id="@+id/ImageView_icon"
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       android:layout_centerVertical="true"
       android:layout_marginLeft="10px"
       android:src="@drawable/main_new"
   />
   <CheckedTextView android:id="@+id/listTextView1"
   xmlns:android="http://schemas.android.com/apk/res/android"
   android:layout_width="wrap_content"
   android:layout_height="wrap_content"
   android:textColor="@drawable/green"
   >
   </CheckedTextView>
   <CheckedTextView android:id="@+id/listTextView2"
   xmlns:android="http://schemas.android.com/apk/res/android"
   android:layout_width="wrap_content"
   android:layout_height="wrap_content"
   android:textColor="@drawable/green"
   android:text="-----自訂"
   >
   </CheckedTextView>
</LinearLayout>
也就是前面擺放一張固定的圖,在顯示的內容後面加上"-----自訂"文字。
 綁定的程式碼:
 
 
 複製代碼String[] item = new String[] {"Ola的家", "魔獸世界","星海爭霸2","凱蘭迪亞傳奇","Ola Query簡介","蟲族秒滅心法","Ola MapGuide教學","Ola jQuery教學","Ola Android教學"};
ArrayAdapter adapter = new ArrayAdapter(this, R.layout.sample_list,R.id.listTextView1,item); 
Olalist.setAdapter(adapter);
 執行結果:
 
   如果看到上面的內容,想到的事情應該是:
 A. 圖片可以依照項目不同嗎?
 B. 第二個文字可以也直接用帶入的嗎?
 
 答案是當然可以,但是使用ArrayAdapter可能不是最佳選擇,因為他一次綁定的數據為一個Array,對於其他內容的顯示可能就不是這麼方便,可是一切都還是可以藉由改寫的方式完成。
 
 出處
 
 | 
 |