Android spinner control and androidspinner Control
The spinner control is a drop-down control in Android. It is used in two ways. First, get the drop-down value from the resource file; second, get the drop-down value from the code.
First, write the value in the resource file:
<? Xml version = "1.0" encoding = "UTF-8"?> <Resources> <string name = "app_name"> spinner </string> <string name = "action_settings"> Settings </string> <string name = "hello_world"> Hello world! </String> <array name = "city"> <item> Shanghai </item> <item> Beijing </item> <item> Guangzhou </item> </array> </resources>
Introduce the written values in the resource file to the layout file:
<Spinner android:id="@+id/spinner1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentLeft="true" android:layout_alignParentTop="true" android:layout_marginLeft="22dp" android:layout_marginTop="49dp" android:entries="@array/city" />
In this way, the first method is complete.
Method 2:
Package com. example. spinner; import android. OS. bundle; import android. app. activity; import android. view. menu; import android. view. view; import android. view. view. onClickListener; import android. widget. adapterView; import android. widget. adapterView. onItemSelectedListener; import android. widget. arrayAdapter; import android. widget. button; import android. widget. spinner; import android. widget. toast; public class Mai NActivity extends Activity {private Spinner sp; private Button btn; String cardNumber; @ Override protected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. activity_main); sp = (Spinner) findViewById (R. id. spinner1); final String [] roles = {"Administrator", "member", "visitor"}; ArrayAdapter <String> adapter = new ArrayAdapter <String> (this, android. r. layout. simple_dropdow N_item_1line, android. r. id. text1, roles); sp. setAdapter (adapter); // The monitoring event sp. setOnItemSelectedListener (new OnItemSelectedListener () {@ Override public void onItemSelected (AdapterView <?> Arg0, View arg1, int arg2, long arg3) {cardNumber = MainActivity. this. getResources (). getStringArray (R. array. city) [arg2]; // cardNumber = roles [arg2]; // set to display the currently selected item // arg0.setVisibility (View. VISIBLE) ;}@ Override public void onNothingSelected (AdapterView <?> Arg0) {// method stub automatically generated by TODO}); // Button listening event btn = (Button) findViewById (R. id. button1); btn. setOnClickListener (new OnClickListener () {@ Override public void onClick (View arg0) {// TODO automatically generated method stub Toast. makeText (MainActivity. this, cardNumber, Toast. LENGTH_SHORT ). show ();}});}}