Spinner is the drop-down menu.
Implementing the Spinner component in Android requires the following three steps:
1. Define the label in the XML file spinner
<Spinner android:id="@+id/spinner" android:layout_width="match_parent" android:layout_height="wrap_content" <!--其它属性略--> />
2. Declare items in the Strings.xml file
<resources ; <string name = "item1" ; item1</string <string name = "item2" ; item2</ string ; <string name = "Item3" ; Item3</string ; <!-- other item omitted--> </rresources ;
3.Java Code Implementation Controller
We need baseadapter to pass string data to the spinner UI component, and implementation Baseadapter must override some methods.
Examples of code slices:
//Data fieldsSpinner Spinner;int[] messageids={r.string.item1,r.string.item2,r.string.item3};//drop-down menu spinner Items Resources //Cover OnCreate () method @Override Public void onCreate(Bundle savedinstancestate) { This. Requestwindowfeature (Window.feature_no_title);//Remove title bar Super. OnCreate (Savedinstancestate); Setcontentview (R.layout.register); Processspinner ();//Processing drop-down menu spinner}//This method is used to process the drop-down list spinner Private void Processspinner() {spinner= (spinner) Findviewbyid (R.id.spinner);//adapter as an adapter for spinnerBaseadapter baseadapter=NewBaseadapter () {@Override PublicViewGetView(intPosition, View Convertview, ViewGroup parent) {TextView spinneritemtextview=NewTextView (Register. This); Spinneritemtextview.settext (" "+getresources (). GetText (Messageids[position]); Spinneritemtextview.settextcolor (Color.Black); Spinneritemtextview.settextsize ( -);returnSpinneritemtextview; }@Override Public Long Getitemid(intARG0) {//TODO auto-generated method stub return 0; }@Override PublicObjectGetItem(intARG0) {//TODO auto-generated method stub return NULL; }@Override Public int GetCount() {//TODO auto-generated method stub return 3; } }; Spinner.setadapter (Baseadapter);//Set adapter for spinner}
If you want to set a click event for spinner items, you can do this:
spinner.setonitemselectedlistener (new Onitemselectedlistener () { @Override public void onitemselected (adapterview<? > Parent, view view, int position, long ID) {String str=parent.getitematposition (position). ToString (); Toast.maketext (Spinneractivity. This , "you clicked:" +str, 2000 ). Show (); } @Override public void onnothingselected (adapterview<?> parent) {//TODO auto-generated Method stub }});
Attention:
In fact, a string resource can also be written in another form:
<stringname="spinnername"> <item>北京</item> <item>上海 </item> <item>广州</item> <item>深圳</item> </string-array>
In the corresponding Java code, a string array is created instead of a string ID array.
// 建立String数组存储Spinner数据String[] mItems = getResources().getStringArray(R.array.spinnername);
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Use of components (i) Use of spinner