1.构建Spinner
<Spinner android:id="@+id/spnSex"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:prompt="@string/spnSexPrompt"
android:spinnerMode="dialog"
/>
其中,promt属性是设置显示在选项列表上方的说明.
2.添加数据
![]()
String[] sSexListStrings=new String[]{"男","女"};
ArrayAdapter<String> adapSexList=new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item,sSexListStrings);
adapSexList.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spnSex.setAdapter(adapSexList);
其中,android.R.layout.simple_spinner_dropdown_item为Spinner的下拉项的样式定义,这里用的是预定义的样式文件,也可以自定义一个
Layout文件,然后用adapSexList.setDropDownViewResource(R.layout.你的Layout文件)的方式进行设置。
3.添加监听事件
![]()
Spinner.OnItemSelectedListener spnSexItemSelectedListener=new Spinner.OnItemSelectedListener(){
@Override
public void onItemSelected(AdapterView<?> parent, View v, int position,
long id) {
// TODO Auto-generated method stub
sSex=parent.getSelectedItem().toString();
}
@Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
};
4.绑定事件
spnSex.setOnItemSelectedListener(spnSexItemSelectedListener);