标签:
android:Spinner(下拉框)控件的使用
创建页面文件(main.xml)
1 <Spinner
2 android:id="@+id/spinner1"
3 android:layout_width="match_parent"
4 android:layout_height="wrap_content" />
5
6 <TextView
7 android:id="@+id/tvResult"
8 android:layout_width="match_parent"
9 android:layout_height="wrap_content"
10 android:text="选择的水果" />
创建下拉框的数据源
1 List<String> list = new ArrayList<String>();
2 list.add("苹果");
5 list.add("香蕉");
7 list.add("橘子");
9 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);
系统提供的样式如下
l simple_spinner_dropdown_item(列表-间距较高比较好看)
clip_image004[10]
l simple_spinner_item(列表-间距紧凑不好看)
clip_image006[10]
l simple_list_item_checked(复选框-选中的有绿沟)
clip_image008[10]
l simple_list_item_single_choice (单选按钮)
clip_image010[10]
向控件Spinner添加适配器
1 Spinner sp=(Spinner) findViewById(R.id.spinner1);
2 sp.setAdapter(adapter);
释义
1. setAdapter(SpinnerAdapter adapter) ,从类的继承关系上看,ArrayAdapter是SpinnerAdapter接口的间接实现类
clip_image012[10]
实现选择项事件(使用匿名类实现接口)
1 sp.setOnItemSelectedListener(new OnItemSelectedListener() {
2 // parent: 为控件Spinner view:显示文字的TextView position:下拉选项的位置从0开始
3 public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
4 TextView tvResult = (TextView) findViewById(R.id.tvResult);
5 //获取Spinner控件的适配器
6 ArrayAdapter<String> adapter = (ArrayAdapter<String>) parent.getAdapter();
7 tvResult.setText(adapter.getItem(position));
8 }
9 //没有选中时的处理
10 public void onNothingSelected(AdapterView<?> parent) {
11 }
12 });
后台整体代码如下
1 public void onCreate(Bundle savedInstanceState) {
2 super.onCreate(savedInstanceState);
3 setContentView(R.layout.main);
4 List<String> list = new ArrayList<String>();
5 list.add("苹果");
6 list.add("香蕉");
7 list.add("橘子");
8 list.add("香蕉");
9 ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, list);
10 adapter.setDropDownViewResource(android.R.layout.simple_list_item_single_choice);
11 Spinner sp = (Spinner) findViewById(R.id.spinner1);
12 sp.setAdapter(adapter);
13 sp.setOnItemSelectedListener(new OnItemSelectedListener() {
14 // parent: 为控件Spinner view:显示文字的TextView position:下拉选项的位置从0开始
15 public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
16 TextView tvResult = (TextView) findViewById(R.id.tvResult);
17 //获取Spinner控件的适配器
18 ArrayAdapter<String> adapter = (ArrayAdapter<String>) parent.getAdapter();
19 tvResult.setText(adapter.getItem(position));
20 }
21 //没有选中时的处理
22 public void onNothingSelected(AdapterView<?> parent) {
23 }
24 });
25 }
标签:
原文地址:http://www.cnblogs.com/dianshi/p/4301308.html