從前面的幾節課可知,ListView用來顯示一個長列表信息,同時把整個屏幕占滿瞭(ListActivity)。但是有的時候,你可能需要其他類似的視圖,這樣,你就不必把整個屏幕都占滿瞭。在這種情況下,你就應該使用Spinner控件。Spinner一次顯示列表中的一個信息,並且它能讓用戶進行選擇。
下面將展示如何在Activity中使用Spinner。
1. 創建一個工程:BasicViews6。
2. main.xml中的代碼。
[html]
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://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中的代碼。
[html]
<?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中的代碼。
[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) { }
});
}
}
5. 按F11在模擬器上調試。在Spinner上面單擊,你將會看到一個彈出的窗口,這個窗口顯示瞭這些名字。選擇一個名字,就會彈出一個信息。
這個例子和ListView很像。你需要實現的方法是onNothingSelected()。當用戶按返回鍵的時候,這個方法被觸發,同時顯示出來的窗口被取消瞭。在這個例子中,我們什麼都沒做,所以沒有實現這個方法。
除瞭顯示一些簡單的列表,也可以顯示RadioButton。隻要修改ArrayAdapter的第二個參數即可。
[java]
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_single_choice, presidents);