XML实现
res/layout/spinner_activity.xml
<Spinner
android:id="@+id/id_sp_xml"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:entries="@array/spinner_activity_xml_education"/>
res/values/array.xml【array.xml类似string.xml】
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string-array name="spinner_activity_xml_education">
<item>高中以下(职高,高中)</item>
<item>大专</item>
<item>本科</item>
<item>硕士/MBA、博士及以上</item>
</string-array>
</resources>
Spinner spinnerXml = (Spinner) findViewById(R.id.id_sp_xml);
spinnerXml.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
int intNum = spinnerXml.getSelectedItemPosition();
String strItem = spinnerXml.getSelectedItem().toString();
Toast.makeText(context,"你选择的是:第"+intNum+"项,"+strItem,Toast.LENGTH_SHORT).show();
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
Toast.makeText(context,"你什么都没有选择!",Toast.LENGTH_SHORT).show();
}
});
代码实现
static final String[] strS={"A型","B型","O型","AB型","其他"};
//将可选内容与ArrayAdapter连接起来
ArrayAdapter<String> adapter = new ArrayAdapter<String>(context,android.R.layout.simple_spinner_item,strS);
//设置下拉列表的风格
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
//将adapter 添加到spinner中
spinnerJava.setAdapter(adapter);
//添加事件Spinner事件监听
spinnerJava.setOnItemSelectedListener(new SpinnerSelectedListener());
//设置是否可见
spinnerJava.setVisibility(View.VISIBLE);
//使用数组形式操作
class SpinnerSelectedListener implements AdapterView.OnItemSelectedListener {
public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
Toast.makeText(context,"你选择的是:第"+arg2+"项"+strS[arg2],Toast.LENGTH_SHORT).show();
}
public void onNothingSelected(AdapterView<?> arg0) {
}
}