The figure below shows an example of how to select a blood type during registration:
First, write a string set in string. xml. The string. xml file mainly contains some text information.
For example, to verify the content and text to be displayed, the code for defining this set is as follows:
<? Xml version = "1.0" encoding = "UTF-8"?>
<Resources>
<String name = "hello"> Hello World, registActivity! </String>
<String name = "app_name"> Registration </string>
<String name = "xuexing"> blood type: </string>
<String-array name = "xuexings">
<Item> A </item>
<Item> B </item>
<Item> O </item>
<Item> AB </item>
</String-array>
</Resources>
Then, write the following content in main. xml:
<Spinner
Android: id = "@ + id/s1"
Android: layout_width = "fill_parent"
Android: layout_height = "wrap_content"
Android: prompt = "@ string/xuexing"
>
</Spinner>
Import android. app. Activity;
Import android. OS. Bundle;
Import android. view. View;
Import android. widget. AdapterView;
Import android. widget. AdapterView. OnItemSelectedListener;
Import android. widget. ArrayAdapter;
Import android. widget. Spinner;
Import android. widget. Toast;
Public class MainHelloSpinner extends Activity
{
@ Override
Public void onCreate (Bundle savedInstanceState)
{
Super. onCreate (savedInstanceState );
SetContentView (R. layout. main );
// Find the drop-down list defined in Xml
Spinner spinner = (Spinner) findViewById (R. id. s1 );
// Prepare an array Adapter
ArrayAdapter adapter = ArrayAdapter. createFromResource (
This, R. array. xuexings, android. R. layout. simple_spinner_item );
// Set the drop-down style. android provides you with a wide range of styles and functional images.
Adapter. setDropDownViewResource (android. R. layout. simple_spinner_dropdown_item );
// Set the adapter for the drop-down list
Spinner. setAdapter (adapter );
// Define the listener for selecting child elements
OnItemSelectedListener oisl = new OnItemSelectedListener ()
{
@ Override
Public void onItemSelected (AdapterView <?> Parent, View view, int position, long id)
{
Toast. makeText (MainHelloSpinner. this, "selected blood type:" +
Parent. getItemAtPosition (position). toString (), Toast. LENGTH_LONG). show ();
}
@ Override
Public void onNothingSelected (AdapterView <?> Parent ){}
};
// Bind an event listener to the drop-down list
Spinner. setOnItemSelectedListener (oisl );
}
}
From running snails