Android: Use of the Spinner (drop-down box) Control
1.
2.Create a page file(Main. xml)
3. Create a data source in the drop-down list
List
List = new ArrayList
(); List. add ("apple"); list. add ("banana"); list. add ("orange"); list. add ("banana ");
4.Create an adapter (the data source in the drop-down list is from the adapter)
ArrayAdapter
adapter=new ArrayAdapter
(this, android.R.layout.simple_spinner_item,list);
5. Add a style for the adapter
Adapter. setDropDownViewResource (android. R. layout. simple_spinner_dropdown_item );
The system provides the following styles:
L simple_spinner_dropdown_item (list-relatively nice-looking with high spacing)
L simple_spinner_item (list-compact spacing is hard to see)
L simple_list_item_checked (check box-selected green ditch)
L simple_list_item_single_choice (single choice button)
6.To control the SpinnerAdd an adapter
Spinner sp = (Spinner) findViewById (R. id. spinner1 );
sp.setAdapter(adapter);
Meaning
1. setAdapter (SpinnerAdapteradapter). From the inheritance relationship of the class, ArrayAdapter is an indirect implementation class of the SpinnerAdapter interface.
7. Implement the selected event (using the Anonymous class to implement the interface)
Sp. setOnItemSelectedListener (new OnItemSelectedListener () {// parent: For the control Spinner view: TextView position of the displayed text: the position of the drop-down option starts from 0 public void onItemSelected (AdapterView
Parent, View view, int position, long id) {TextView tvResult = (TextView) findViewById (R. id. tvResult); // obtain the ArrayAdapter of the Spinner Control
Adapter = (ArrayAdapter
) Parent. getAdapter (); tvResult. setText (adapter. getItem (position);} // process public void onNothingSelected (AdapterView
Parent ){}});
8. The overall background code is as follows:
Public void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. main); List
List = new ArrayList
(); List. add ("apple"); list. add ("banana"); list. add ("orange"); list. add ("banana"); ArrayAdapter
Adapter = new ArrayAdapter
(This, android. r. layout. simple_spinner_item, list); adapter. setDropDownViewResource (android. r. layout. simple_list_item_single_choice); Spinner sp = (Spinner) findViewById (R. id. spinner1); sp. setAdapter (adapter); sp. setOnItemSelectedListener (new OnItemSelectedListener () {// parent: For the control Spinner view: TextView position of the displayed text: the position of the drop-down option starts from 0 public void onItemSelected (AdapterView
Parent, View view, int position, long id) {TextView tvResult = (TextView) findViewById (R. id. tvResult); // obtain the ArrayAdapter of the Spinner Control
Adapter = (ArrayAdapter
) Parent. getAdapter (); tvResult. setText (adapter. getItem (position);} // process public void onNothingSelected (AdapterView
Parent ){}});}