Adapter 适配器
//方法一:直接使用字符串数组
//String[] sSexList = new String[]{"男", "女"};
//方法二:使用资源文件
String[] sSexList = getResources().getStringArray(R.array.Sexarray);
//实例化一个集合适配器
ArrayAdapter<String> adapter =
newArrayAdapter<String>(MainActivity.this, android.R.layout.simple_spinner_item, sSexList);
//给Spinner 设置适配器
spnSex.setAdapter(adapter);
//给Spinner 注册一个监听器
spnSex.setOnItemSelectedListener(new OnItemSelectedListener() {
//parent 是适配器, View是你当前选择的view, position 在Adapter数组中的位置角标
//id 就是你选中的id
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
// TODO Auto-generated method stub
sSex = parent.getSelectedItem().toString();
}
//只要其它选项没被选择就会触发
public void onNothingSelected(AdapterView<?> parent) {
}
});
1
2
3 Layout 属性
4
5 <Spinner
6 android:id="@+id/spnSex"
7 android:layout_width="fill_parent"
8 android:layout_height="wrap_content"
9 android:prompt="@string/prompt"
10 />
11
12
13 string-array 资源文件
14
15 <?xml version="1.0" encoding="utf-8"?>
16 <resources>
17 <string-array name="Sexarray">
18 <item >男</item>
19 <item >女</item>
20 </string-array>
21 </resources>
22
23