Spinner 學習筆記

Adapter 適配器 //方法一:直接使用字符串數組 //String[] sSexList = new String[]{"男", "女"}; //方法二:使用資源文件
       String[] sSexList = getResources().getStringArray(R.array.Sexarray); //實例化一個集合適配器
       ArrayAdapter<String> adapter = newArrayAdapter<String>(MainActivity.this, android.R.layout.simple_spinner_item, sSexList); //給Spinner 設置適配器
 spnSex.setAdapter(adapter); //給Spinner 註冊一個監聽器
      spnSex.setOnItemSelectedListener(new OnItemSelectedListener() { //parent 是適配器, View是你當前選擇的view, position 在Adapter數組中的位置角標 //id 就是你選中的id
        public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { // TODO Auto-generated method stub
            sSex = parent.getSelectedItem().toString(); } //只要其它選項沒被選擇就會觸發
        public void onNothingSelected(AdapterView<?> parent) { }    });
View Code

 

 1    
 2    
 3 Layout 屬性  4 
 5 <Spinner  6     android:id="@+id/spnSex"
 7  android:layout_width="fill_parent"
 8  android:layout_height="wrap_content"
 9  android:prompt="@string/prompt"
10    />
11    
12 
13 string-array 資源文件 14 
15 <?xml version="1.0" encoding="utf-8"?>
16 <resources>
17     <string-array name="Sexarray">
18         <item ></item>
19         <item ></item>
20     </string-array>
21 </resources>
22 
23    
View Code
相關文章
相關標籤/搜索