從前面的幾節課可知,ListView用來顯示一個長列表資訊,同時把整個螢幕佔滿了(ListActivity)。但 是有的時候,你可能需要其他類似的視圖,這樣,你就不必把整個螢幕都佔滿了。在這種情況下,你就應該 使用Spinner控制項。Spinner一次顯示列表中的一個資訊,並且它能讓使用者進行選擇。
下面將展示如何 在Activity中使用Spinner。
1. 建立一個工程:BasicViews6。
2. 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:orientation="vertical" > <Spinner android:id="@+id/spinner1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:drawSelectorOnTop="true" /> </LinearLayout>
3. strings.xml中的代碼。
<?xml version="1.0" encoding="utf-8"?> <resources> <string name="hello">Hello World, BasicViews6Activity!</string> <string name="app_name">BasicViews6</string> <string-array name="presidents_array"> <item>Dwight D. Eisenhower</item> <item>John F. Kennedy</item> <item>Lyndon B. Johnson</item> <item>Richard Nixon</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>Barack Obama</item> </string-array> </resources>
4. BasicViews6Activity.java中的代碼。
public class BasicViews6Activity extends Activity { String[] presidents; /** Called when the activity is first created. */ @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) { } }); } }