1.Spinner的簡介
Spinner(下拉列表)是一個每次只能選擇所有項中一項的控件,相當於Html中的下拉列表框。它的繼承關系如下:
java.lang.Object
↳ Android.view.View
↳ android.view.ViewGroup
↳ android.widget.AdapterView<T extends android.widget.Adapter>
↳ android.widget.AbsSpinner
↳ android.widget.Spinner
Spinner常用的XML屬性:
屬性名稱
描述
android:prompt
該提示在下拉列表對話框顯示時顯示。(譯者注:對話框的標題:
650) this.width=650;">
2.創建使用Spinner的步驟如下:
①需要在布局中定時Spinner組件,然後向Spinner添加需要選擇的數據
②設置事件監聽器setOnItemSelectedListener( )並實現onItemSelected( )
3.Spinner添加數據的兩種方法:
①在Java代碼中載入列表數據
具體的例子如下:
MainActivity.java
- package com.android.spinner;
- import android.app.Activity;
- import android.os.Bundle;
- import android.view.View;
- import android.widget.AdapterView;
- import android.widget.ArrayAdapter;
- import android.widget.Spinner;
- import android.widget.TextView;
- public class MainActivity extends Activity {
- private static final String[] province={"廣東","廣西","湖南","河南","福建"};
- private TextView text;
- private Spinner spinner;
- private ArrayAdapter<String> adapter;
- @Override
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.main);
- text=(TextView)findViewById(R.id.text);
- spinner=(Spinner)findViewById(R.id.spinner);
- //將Spinner裡面的可選擇內容通過ArrayAdapter連接起來
- adapter=new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item,province);
- //設置Spinner的樣式
- adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
- //為對話框設置標題
- //也可在XMl文件中通過“android:prompt”設置
- spinner.setPrompt("你來自哪個省");
- //為Spinner設置適配器
- spinner.setAdapter(adapter);
- //添加Spinner事件監聽
- spinner.setOnItemSelectedListener(new Spinner.OnItemSelectedListener(){
- @Override
- public void onItemSelected(AdapterView<?> arg0, View arg1,
- int arg2, long arg3) {
- // TODO Auto-generated method stub
- text.setText("你所在的城市是:"+province[arg2]);
- //設置顯示當前選擇的項
- arg0.setVisibility(View.VISIBLE);
- }
- @Override
- public void onNothingSelected(AdapterView<?> arg0) {
- // TODO Auto-generated method stub
- }
- });
- }
- }