使用spinner组件,android:entries用于指定列表项,如果布局文件不指定该属性,android:prompt用于指定列表选择框的的标题,在android(4.0)中采用默认主题是设置该属性看不到具体效果,如果采用Theme.Black,就可以在弹出下拉框中显示该标题
布局代码:
<Spinner
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/spinner1"
android:prompt="@+string/spinner"
android:entries="@+array/ctype"/>
创建用于指定列表项的数组资源文件,将其保存在values/arrays目录中
代码如下:
<resources>
<string-array name = "ctype">
<item>身份证</item>
<item>学生证</item>
<item>军人证</item>
<item>工作证</item>
<item>其他</item>
</string-array>
2.监听事件:
getSelectedItem()方法获取列表选择框的选中项,为列表选择框添加OnItemSelectedListener事件监听器
java代码:
Spinner spinner = (Spinner)findViewById(R.id.spinner1);
spinner.getSelectedItem();
spinner.setOnItemSelectedListener(new OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View arg1, int pos, long id) {
String result = parent.getItemAtPosition(pos).toString();
Log.i("Spinner 示例", result);
}
@Override
public void onNothingSelected(AdapterView<?> arg0) {
}
});
3.如果在布局文件没有指定android:entries属性,可以在java代码中通过适配器的方式指定
String[] ctype=new String[]{"身份证","学生证","军人证","工人证","其他"};
ArrayAdapter<String> adapter1=new ArrayAdapter<String>(this,android.R.layout.simple_spinner_dropdown_item,ctype);
adapter1.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter1);
![](http://dl2.iteye.com/upload/attachment/0110/9460/a3ff0aa6-a938-3890-92cd-365cd50306ba.jpg)
![](http://dl2.iteye.com/upload/attachment/0110/9462/ec682094-bcae-377b-86ea-e115f84675af.jpg)