Spinner是一個列表選擇框,但其並不需要顯示下拉列表,二十相當於一個菜單供用戶選擇,下面用一個例子介紹:
在樣式文件中:
- <?xml version="1.0" encoding="utf-8"?>
- <LinearLayout xmlns:Android="http://schemas.android.com/apk/res/android"
- android:layout_width="match_parent"
- android:layout_height="match_parent"
- android:orientation="vertical" >
-
- <TextView
- android:layout_width="fill_parent"
- android:layout_height="wrap_content"
- android:text="請選擇一項運動項目"
- />
- <Spinner
- android:id ="@+id/sportsSp"
- android:layout_width="match_parent"
- android:layout_height="wrap_content"
- android:prompt="@string/spinner_prompt"
- android:entries="@array/sports"
- />
-
- </LinearLayout>
在<Spinner>標簽中,通過android:prompt來設置彈出選擇框的標題,通過android:entries來設置默認的列表選項(定義在一個arrays.xml文件中)
- <?xml version="1.0" encoding="utf-8"?>
- <resources>
- <string-array name="sports" >
- <item>足球</item>
- <item>籃球</item>
- <item>乒乓球</item>
- <item>網球</item>
- </string-array>
- </resources>
監聽列表點擊事件:
- package cn.class3g.activity;
-
- import android.app.Activity;
- import android.os.Bundle;
- import android.util.Log;
- import android.view.View;
- import android.widget.AdapterView;
- import android.widget.AdapterView.OnItemSelectedListener;
- import android.widget.Spinner;
- import android.widget.TextView;
-
- public class SpinnerDemo extends Activity implements OnItemSelectedListener{
- Spinner sportSp = null;
-
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.spinner_layout);
- findViews();
- }
-
- private void findViews() {
- sportSp = (Spinner)this.findViewById(R.id.sportsSp);
- sportSp.setOnItemSelectedListener(this);
- sportSp.performClick();
- }
- //每選擇一次均以日志輸出形式打印
- public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2,
- long arg3) {
- TextView tv = (TextView) arg1;
- Log.i("TAG", tv.getText().toString());
- }
-
- public void onNothingSelected(AdapterView<?> arg0) {
- }
- }
在模擬器中的效果與日志輸出結果: