Simple implementation of data binding for a spinner in Android

Source: Internet
Author: User

 

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.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.