這文章是看完Mars 老師的教學視頻後根據自己理解寫的,所以部分內容引用到Mars 老師視頻。
ps :極力推薦初學android的朋友看Mars老師的視頻。
本文:
spinner控制項就好比如我們電腦的下拉選擇菜單,但由於手機螢幕的顯示範圍有限,所以就會彈出一個類似於對話方塊的選擇菜單。如:
-------------------------------->
第二就是構造spinner控制項的步奏:
1.在布局檔案中聲明資訊(如ID,寬高背景等)
<spinner android:"@+id/spinner" android:layout_wight="fill_parent" android:layout_height="wrap_content"/>
2.在string.xml中聲明一個數組,這個數組是彈出選擇菜單的選項文字
<string-array name="planets_array"> <item>Mercury</item> <item>Venus</item> <item>Earth</item> <item>Mars</item> <item>Jupiter</item> <item>Saturn</item> <item>Uranus</item> <item>Neptune</item> </string-array>
3.建立一個Arryadapter對象。並調用兩個方法
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this, R.array.planets_array, android.R.layout.simple_spinner_item);adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
其中createFromResource方法中有三個參數,分別表示:
this:內容物件,
R.array.planets_array:引用在string.xml中聲明的數組;
android.R.layout.simple_spinner_item:設定主題;
其中setDropDownViewResource
方法是用來設定spinner中每一個選項的主題;
4.得到一個spinner 對象然後設定對象的資料:
spinner.setaAdapter(adapter);//把上面設定好的adapter傳進spinner中(相當於快顯功能表的內容);spinner.setPrompt("測試");//快顯功能表的描述
第三是設定監聽器來監聽spinner的動作:
class spinnerListener implements OnItemSelectedListener { ... public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) { // An item was selected. You can retrieve the selected item using // parent.getItemAtPosition(pos) } public void onNothingSelected(AdapterView<?> parent) { // Another interface callback }}
OnItemSelectedListener
類中可以複寫兩個函數:
1.void
onItemSelected :使用者選中了菜單中的某一項後程式要執行的動作(其中傳入參數int pos就是被選中選項在菜單中的位置)
2.void onNothingSelected :當使用者什麼都沒有選中的情況下要執行的動作;
附加:上面說的是靜態設定選擇菜單中的內容,也就是說菜單中的選中是固定不可變的,但實際應用上很多時候選項是需要隨著使用者的操作而改變的,所以android就有一個動態設定ArrayAdapter的方法:
過程是先設定一個List<T>的對象,再建立一個ArrayAdapter對象的建構函式:
public ArrayAdapter (Context context, int resource, int textViewResourceId, T[] objects)
傳入四個參數:
1.context:內容物件;
2.resource:設定菜單的樣式(就是主題一般為R.layout.item的ID);
3.textViewResourceId:指定textView空間的ID;
4.T[] objects:就是上面設定的List對象;