In Android, spinner is usually used to implement the drop-down list. Unfortunately, it does not directly implement automatic binding like text-value. In some cases, the text displayed in the list is not the value we want to obtain, so we need to manually bind the data. First, two arrays are used to represent the displayed text and the value to be taken,CodeAs follows:
Private Final StaticString [] texts = {"Zhang San", "Li Si", "Wang Wu"};Private Final Static Int[] Values = {1, 2, 3};PrivateSpinner spinner;PrivateArrayadapter <string> adapter;
Here, texts is the text displayed in the drop-down list, and values is the value specified after the list is selected. The Code is as follows:
Spinner =(Spinner) findviewbyid (R. Id. spinner ); // Bind the texts to display Adapter = New Arrayadapter <string> ( This , Android. R. layout. simple_spinner_item, texts ); // Set the style of the drop-down list
Adapter. setdropdownviewresource (Android. R. layout. simple_spinner_dropdown_item ); Spinner. setadapter (adapter); spinner. setonitemselectedlistener ( New Spinnerselectedlistener (); spinner. setvisibility (view. Visible ); Class Spinnerselectedlistener Implements Onitemselectedlistener { Public Void Onitemselected (adapterview <?> Arg0, view arg1, Int Arg2, Long Arg3 ){ // Use the corresponding position in the array to obtain the value required in values IntID= Values [arg2] ;}}
In addition, you can also use the spinner. getselecteditem (). tostring () to obtain the selected text, or use the spinner. getselecteditemposition () to obtain the position of the selected text. getselecteditemposition ()] to obtain the corresponding value.
If your list data is dynamically obtained. You can use arraylist instead of array to add it dynamically.