我的作法是先將要塞入Spinner的字串輸入在xml檔案
在透過ArrayAdapter將資料橋接近去
Code:
package com.cyfang.myspinner; import android.app.Activity; import android.os.Bundle; import android.widget.ArrayAdapter; import android.widget.Spinner; public class SpinnerMain extends Activity { private Spinner spinner = null; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_spinner_main); spinner = (Spinner) findViewById(R.id.spinner1); ArrayAdapter<CharSequence> arrayAdapter = ArrayAdapter .createFromResource(this, R.array.StudentList, android.R.layout.simple_spinner_item); arrayAdapter .setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); spinner.setAdapter(arrayAdapter); } }
array.xml:
<?xml version="1.0" encoding="utf-8"?> <resources> <string-array name="StudentList"> <item >國小</item> <item >國中</item> <item >高中</item> <item >大學</item> <item >碩士</item> <item >博士</item> <item >博士後</item> </string-array> </resources>
那如果不透過xml檔案,則可以在程式裡面宣告一個String陣列,建構一個ArrayAdapter並將String陣列塞到ArrayAdapter方法裡頭就可以了
package com.cyfang.myspinner; import android.app.Activity; import android.os.Bundle; import android.widget.ArrayAdapter; import android.widget.Spinner; public class SpinnerMain extends Activity { private Spinner spinner = null; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_spinner_main); spinner = (Spinner) findViewById(R.id.spinner1); String[] str = new String[] { "國小", "國中", "高中", "大學", "碩士", "博士" }; ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, str); arrayAdapter .setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); spinner.setAdapter(arrayAdapter); } }