As you can see from the previous lessons, ListView is used to display a long list of information while filling the entire screen (listactivity). But sometimes, you might want to have other similar views, so you don't have to fill up the entire screen. In this case, you should use the spinner control. Spinner displays one message in the list at a time, and it allows the user to choose.
The following shows how to use spinner in an activity.
1. Create a project: BASICVIEWS6.
2. Code in the Main.xml.
<?xml version= "1.0" encoding= "Utf-8"?> <linearlayout xmlns:android=
"http://schemas.android.com/apk/" Res/android "
android:layout_width=" fill_parent "
android:layout_height=" fill_parent "
android:o" rientation= "vertical" >
<spinner
android:id= "@+id/spinner1" android:layout_width= "WRAP_"
Content "
android:layout_height=" wrap_content "
android:drawselectorontop=" true "/>
</ Linearlayout>
3. Code in the Strings.xml.
<?xml version= "1.0" encoding= "Utf-8"?> <resources> <string name= "Hello" >hello worl D, basicviews6activity!</string> <string name= "App_name" >BasicViews6</string> <st Ring-array name= "Presidents_array" > <item>dwight D. eisenhower</item> <item& Gt John F. kennedy</item> <item>lyndon B. johnson</item> <item>richard Ni
xon</item> <item>gerald ford</item> <item>jimmy carter</item>
<item>ronald reagan</item> <item>george H. W bush</item> <item>bill clinton</item> <item>george W. bush</item> <item>bara CK obama</item> </string-array> </resources>
The code in
4. Basicviews6activity.java.
public class Basicviews6activity extends activity {string[] presidents; /** called the activity is a.
* * @Override public void onCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);
Setcontentview (R.layout.main);
Presidents = Getresources (). Getstringarray (R.array.presidents_array);
Spinner S1 = (Spinner) Findviewbyid (r.id.spinner1); arrayadapter<string> adapter = new Arrayadapter<string> (this, Android.
R.layout.simple_spinner_item, Presidents);
S1.setadapter (adapter); S1.setonitemselectedlistener (New Onitemselectedlistener () {@Override public
void onitemselected (adapterview<?> arg0, View arg1, int arg2, long arg3) { int index = arg0.getselecteditemposition ();
Toast.maketext (Getbasecontext (), "You have selected item:" + Presidents[index],
Toast.length_short). Show ();
@Override public void onnothingselected (Adapterview<?> arg0) {}
}); }
}