1、在布局文件当中声明
<Spinner
android:id="@+id/spinnerId"
android:layout_width="fill_parent"
android:layout_height="wrap_content"></Spinner>
<TextView
android:id="@+id/result"
android:layout_width="fill_parent"
android:layout_height="wrap_content">
2、在Strings.xml中声明一个数组
<string-array name="HolidayType_array">
<item>病假</item>
<item>休假</item>
<item>年假</item>
<item>婚假</item>
</string-array>
3、创建一个ArrayAdapter
ArrayAdapter<CharSequence> adapter=ArrayAdapter.createFromResource(
this, //上下文对象
R.array.HolidayType_array, //在strings.xml中定义的那个数组
android.R.layout.simple_spinner_item //布局文件(Android自带的,定义下拉菜单是什么样子的)
);
adapter.setDropDownViewResource(
android.R.layout.simple_spinner_dropdown_item //定义每一个选项是什么样子
);
4、得到Spinner对象,并设置数据
spinner=(Spinner)this.findViewById(R.id.spinnerId);
result=(TextView)this.findViewById(R.id.result);
//为Spinner绑定数据
spinner.setAdapter(adapter);
spinner.setPrompt("请假类型");
5、为Spinner创建一个监听器,输出选中项
//为Spinner创建监听器
spinner.setOnItemSelectedListener(new OnItemSelectedListener(){
@Override
public void onItemSelected(AdapterView<?> arg0, View arg1,
int arg2, long id) {
String selected=arg0.getItemAtPosition(arg2).toString(); //得到选中的项
result.setText(selected); //将结果放入到TextView中
}
@Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});