1、UI文件:spinner.xml
<?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:id="@+id/textView1" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="TextView" /> <Spinner android:id="@+id/spinner1" android:layout_width="fill_parent" android:layout_height="wrap_content" android:drawSelectorOnTop="true" android:prompt="@string/city_message" /> </LinearLayout>
2、SpinnerAcitivity.java文件
public class SpinnerActivity extends Activity{ private Spinner spinner; private static final String[] CITY = { "Spinner Item1", "Spinner Item2", "Spinner Item3", "Spinner Item4" }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.spinner); spinner = (Spinner) findViewById(R.id.spinner1); ArrayAdapter<String> adapter = new ArrayAdapter<String>( this,android.R.layout.simple_spinner_item,CITY); spinner.setAdapter(adapter); spinner.setOnItemSelectedListener( new AdapterView.OnItemSelectedListener(){ public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3) { Toast.makeText(SpinnerActivity.this, CITY[arg2], Toast.LENGTH_SHORT).show(); } public void onNothingSelected(AdapterView<?> arg0){} }); } }
3. 效果图。 使用模拟器。