Go Spinner drop-down list in Android (implemented with Arrayadapter and custom adapter)

Source: Internet
Author: User

Today I learned the spinner component, using spinner as the equivalent of selecting a project from the drop-down list, the following shows the use of spinner (using Arrayadapter and custom adapter implementations respectively)

(a): Use Arrayadapter to fit data:

①: First define a layout file:

1 <spanstyle= "FONT-SIZE:16PX;"><?XML version= "1.0" encoding= "Utf-8"?>2 <LinearLayoutxmlns:android= "Http://schemas.android.com/apk/res/android"3 Android:layout_width= "Fill_parent"4 Android:layout_height= "Fill_parent"5 android:orientation= "vertical" >6  7     <Spinner8         Android:id= "@+id/spinner1"9 Android:layout_width= "Match_parent"Ten Android:layout_height= "Wrap_content" One       /> A </LinearLayout></span>

"Note:" The above spinner has two properties 1:prompt is the initial time, spinner displays the data, is a reference type 2:entries is to bind the data source directly in the XML layout file (can not be set, that can be dynamically bound in the activity)

②: Create a data source, use an array, and the data will be displayed in the spinner down list:

1 <spanstyle= "FONT-SIZE:16PX;"><?XML version= "1.0" encoding= "Utf-8"?>2 <Resources>3     <String-arrayname= "Spinnername">4         <Item>Beijing</Item>5         <Item>Shanghai</Item>6         <Item>Guangzhou</Item>7         <Item>Shenzhen</Item>8     </String-array>9 </Resources></span>

③: Then add the following code to the activity ( using a system-defined drop-down list of layout files, of course, can also be customized)

       // Initialize control mspinner = (Spinner) Findviewbyid (r.id.spinner1); // set up a data source string[] Mitems = getresources (). Getstringarray (r.array.spinnername); // establish adapter and bind the data source arrayadapter<string> _adapter=New arrayadapter<string> (this, Android. R.layout.simple_spinner_item, mitems); // bind Adapter to control mspinner.setadapter (_adapter);

The above code initially completed, to see the effect of the operation:

Here is a click event about spinner (for example):

Mspinner.setonitemselectedlistener (NewOnitemselectedlistener () {@Override Public voidOnitemselected (adapterview<?>Parent, view view,intPositionLongID) {String str=parent.getitematposition (position). ToString (); Toast.maketext (spinneractivity. This, "You clicked:" +str, 2000). Show (); } @Override Public voidOnnothingselected (adapterview<?>parent) {        //TODO auto-generated Method Stub    }});

(ii) Use of custom adapter (emphasis)

①: Define a layout file for each item

<?XML version= "1.0" encoding= "Utf-8"?><LinearLayoutxmlns:android= "Http://schemas.android.com/apk/res/android"Android:layout_width= "Match_parent"Android:layout_height= "Match_parent"android:orientation= "Horizontal" >     <TextViewAndroid:id= "@+id/textview1"Android:layout_width= "Wrap_content"Android:layout_height= "Wrap_content"Android:drawableleft= "@drawable/ic_launcher"Android:paddingright= "8dip"Android:paddingtop= "8dip"Android:text= "TextView"android:textsize= "25SP" />     <TextViewAndroid:id= "@+id/textview2"Android:layout_width= "Wrap_content"Android:layout_height= "Wrap_content"Android:paddingleft= "8dip"Android:paddingtop= "8dip"Android:text= "TextView"android:textsize= "25SP" /> </LinearLayout>

②: Establish the Person class:

1  Packagecom.jiangqq.csdn;2  Public classPerson {3     PrivateString personname;4     PrivateString personaddress;5      PublicPerson (String personname, String personaddress) {6         Super();7          This. PersonName =PersonName;8          This. personaddress =personaddress;9     }Ten      PublicString Getpersonname () { One         returnPersonName; A     } -      Public voidsetpersonname (String personname) { -          This. PersonName =PersonName; the     } -      PublicString getpersonaddress () { -         returnpersonaddress; -     } +      Public voidsetpersonaddress (String personaddress) { -          This. personaddress =personaddress; +     } A   at}

③: Create Myadapter inheritance and baseadapter to fit:

 Packagecom.jiangqq.csdn;Importjava.util.List;ImportAndroid.content.Context;ImportAndroid.view.LayoutInflater;ImportAndroid.view.View;ImportAndroid.view.ViewGroup;ImportAndroid.widget.BaseAdapter;ImportAndroid.widget.TextView;/*** Custom Adapter class *@authorjiangqq <a href=http://blog.csdn.net/jiangqq781931404></a> **/ Public classMyadapterextendsBaseadapter {PrivateList<person>mlist; PrivateContext Mcontext;  PublicMyadapter (Context PContext, list<person>pList) {         This. Mcontext =PContext;  This. mlist =pList; } @Override Public intGetCount () {returnmlist.size (); } @Override PublicObject GetItem (intposition) {        returnMlist.get (position); } @Override Public LongGetitemid (intposition) {        returnposition; }    /*** Below is the important code*/@Override PublicView GetView (intposition, View Convertview, ViewGroup parent) {Layoutinflater _layoutinflater=Layoutinflater.from (Mcontext); Convertview=_layoutinflater.inflate (R.layout.item,NULL); if(convertview!=NULL) {TextView _textview1=(TextView) Convertview.findviewbyid (R.ID.TEXTVIEW1); TextView _textview2=(TextView) Convertview.findviewbyid (R.ID.TEXTVIEW2);            _textview1.settext (Mlist.get (position). Getpersonname ());        _textview2.settext (Mlist.get (position). Getpersonaddress ()); }        returnConvertview; }}

④: Add the following code to the activity:

       //Initializing the controlMspinner =(Spinner) Findviewbyid (r.id.spinner1);//set up a data sourceList<person> persons=NewArraylist<person>();p Ersons.add (NewPerson ("Zhang San", "Shanghai"));p Ersons.add (NewPerson ("John Doe", "Shanghai"));p Ersons.add (NewPerson ("Harry", "Beijing"));p Ersons.add (NewPerson ("Zhao Liu", "Guangzhou"));//To establish a adapter bound data sourceMyadapter _myadapter=NewMyadapter ( This, persons);//Binding AdapterMspinner.setadapter (_myadapter);

The results are as follows:


The Listener event is the same as the first method:

Transferred from: http://blog.csdn.net/jiangqq781931404/article/details/7285623

Go Spinner drop-down list in Android (implemented with Arrayadapter and custom adapter)

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.