Spinner drop-down list
Step 1: Add a list of drop-down list items. The items added here are the menu items in the drop-down list:
Private List List = new ArrayList ();
List. add (Beijing );
List. add (Shanghai );============ "Data Source
List. add (Guangzhou );
List. add (Shenzhen );
Step 2: Define an array adapter (ArrayAdapter) for the drop-down list. The previously defined list is used here.
Adaoter = new ArrayAdapter (This, android. R. layout. simple_apinner.item, list ); Define the adapter and add a data source
Step 3: Set the menu style when the adapter is added to the drop-down list.
Adapter. setDropDownViewResource (android. R. layout. simple_spinner_dropdown_item );
Step 4: add the adapter to the drop-down list-------------------- "Binner" loads the adapter
MySpinner. setAdapter (adapter );
Step 5: Set events for the drop-down list. The corresponding event menu is selected.
MySpinner. setOnItemSelectedListener (new Spinner. OnItemSelectedListener ())---------------> Set the listener for the spinner
Below is a small example:
One layout:
Xmlns: tools = http://schemas.android.com/tools
Android: layout_width = match_parent
Android: layout_height = match_parent
Tools: context =. MainActivity>
Android: id = @ + id/text
Android: layout_width = fill_parent
Android: layout_height = wrap_content
Android: textColor = #000
Android: textSize = 20dp/>
Android: id = @ + id/spinner
Android: layout_below = @ id/text
Android: layout_width = fill_parent
Android: layout_height = wrap_content
Android: background = #345/>
A java class:
Public class MainActivity extends Activity implements OnItemSelectedListener {
Private String cityName;
Private TextView text;
Private Spinner spinner;
Private List List;
Private ArrayAdapter Adapter;
@ Override
Protected void onCreate (Bundle savedInstanceState ){
Super. onCreate (savedInstanceState );
SetContentView (R. layout. activity_main );
Text = (TextView) findViewById (R. id. text );
Spinner = (Spinner) findViewById (R. id. spinner );
// 1. Set the data source
List = new ArrayList ();
List. add (Beijing );
List. add (Shanghai );
List. add (Guangzhou );
List. add (deep Certificate );
// 2. Create an ArrayAdapter (array adapter)
Adapter = new ArrayAdapter (This, android. R. layout. simple_expandable_list_item_1, list );
// 3. Set a drop-down table style using the adapter
Adapter. setDropDownViewResource (android. R. layout. simple_spinner_dropdown_item );
// 4. Bind the adapter
Spinner. setAdapter (adapter );
// 5. Set the listener for the spinner.
Spinner. setOnItemSelectedListener (this );
}
@ Override
Public void onItemSelected (AdapterView Arg0, View arg1, int arg2,
Long arg3 ){
// TODO Auto-generated method stub
CityName = list. get (arg2 );
Text. setText (the city you selected is + cityName );
}
@ Override
Public void onNothingSelected (AdapterView Arg0 ){
// TODO Auto-generated method stub
}
}