但是在手機螢幕大小,無法讓我們將所有的選項都放進去螢幕中。
所以Android提供了Spinner widget,讓開發者可以在有限的畫面範圍內仍可放入所需的資料。
首先我們先在XMl檔放入兩個Spinner,一個是kind、另一個是name
在程式的功能是
在選擇kind spinner會改變 name spinner顯示的選項
在選取name 的spinner會跳出toast,show出選擇的名稱
程式碼如下
public class MainActivity extends Activity { private ArrayAdapterlistAdapter; private ArrayAdapter nameAdapter; private Spinner kind = null; private Spinner name = null; private String itemname[] = null; //showtoast flag是用來判斷是否 name spinner有被選取 private boolean showtoast=false; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); initui(); listAdapter = new ArrayAdapter (this, R.layout.spinnerlayout, new String[] { "肉類", "蔬菜", "水果" }); //設定下拉式選單顯示的版面 listAdapter.setDropDownViewResource(R.layout.spinner_dropdown); //設定kind spinner顯示的字串內容 kind.setAdapter(listAdapter); //設定當kind spinner item選取後的動作 kind.setOnItemSelectedListener(spinnerlistener); } //初始化UI function private void initui() { kind = (Spinner) findViewById(R.id.kind); name = (Spinner) findViewById(R.id.name); } AdapterView.OnItemSelectedListener spinnerlistener = new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView adapterView, View view, int position, long id) { //當選取的spinner是kind時 if (adapterView.getId() == R.id.kind) { //判斷選取的種類是何種,設定相對應的字串陣列內容 switch (adapterView.getSelectedItemPosition()) { case 0: itemname = new String[] { "牛肉", "豬肉", "雞肉" }; break; case 1: itemname = new String[] { "白菜", "香菜", "高麗菜" }; break; case 2: itemname = new String[] { "蘋果", "香蕉", "西瓜" }; break; } //當itemanme不為空時,對spinner name進行初始化 if (itemname != null) { setnameitem(); } } else if (adapterView.getId() == R.id.name) { if(showtoast!=false) { Toast.makeText(MainActivity.this, "您選擇" + adapterView.getSelectedItem().toString(), Toast.LENGTH_LONG).show(); } showtoast=true; } } @Override public void onNothingSelected(AdapterView arg0) { } }; private void setnameitem() { showtoast=false; nameAdapter = new ArrayAdapter (this, R.layout.spinnerlayout, itemname); name.setAdapter(nameAdapter); name.setOnItemSelectedListener(spinnerlistener); } }
設定Spinner顯示字體格式 spinnerlayout.xml 程式碼如下
設定Spinner下拉式選單版面格式 spinner_dropdown.xml 程式碼如下
程式畫面如下;
參考資料
http://xapps.cc/article/280
http://jim690701.blogspot.tw/2012/11/androidspinner.html
http://stackoverflow.com/questions/4923310/android-spinner-onitemselected-setonitemselectedlistener-not-triggering