标签:
1.效果图
2.创建页面文件(main.xml)
<Spinner
android:id="@+id/spinner1"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<TextView
android:id="@+id/tvResult"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="选择的水果" />
3.创建下拉框的数据源
List<String> list = new ArrayList<String>();
list.add("苹果");
list.add("香蕉");
list.add("橘子");
list.add("香蕉");
4.创建适配器(下拉框的数据源是来自适配器)
ArrayAdapter<String> adapter=new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item,list);
5.为适配器添加样式
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
6.向控件Spinner添加适配器
Spinner sp=(Spinner) findViewById(R.id.spinner1);
sp.setAdapter(adapter);
释义
1. setAdapter(SpinnerAdapter adapter) ,从类的继承关系上看,ArrayAdapter是SpinnerAdapter接口的间接实现类
7.实现选择项事件(使用匿名类实现接口)
sp.setOnItemSelectedListener(new OnItemSelectedListener() {
// parent: 为控件Spinner view:显示文字的TextView position:下拉选项的位置从0开始
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
TextView tvResult = (TextView) findViewById(R.id.tvResult);
//获取Spinner控件的适配器
ArrayAdapter<String> adapter = (ArrayAdapter<String>) parent.getAdapter();
tvResult.setText(adapter.getItem(position));
}
//没有选中时的处理
public void onNothingSelected(AdapterView<?> parent) { }
});
8.后台整体代码如下
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
List<String> list = new ArrayList<String>();
list.add("苹果");
list.add("香蕉");
list.add("橘子");
list.add("香蕉");
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, list);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
Spinner sp = (Spinner) findViewById(R.id.spinner1);
sp.setAdapter(adapter);
sp.setOnItemSelectedListener(new OnItemSelectedListener() {
// parent: 为控件Spinner view:显示文字的TextView position:下拉选项的位置从0开始
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
TextView tvResult = (TextView) findViewById(R.id.tvResult);
//获取Spinner控件的适配器
ArrayAdapter<String> adapter = (ArrayAdapter<String>) parent.getAdapter();
tvResult.setText(adapter.getItem(position));
}
//没有选中时的处理
public void onNothingSelected(AdapterView<?> parent) {
}
});
}
标签:
原文地址:http://www.cnblogs.com/lxcao/p/4298878.html