标签:
1.效果图
2.创建页面文件(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="选择的水果" />
3.创建下拉框的数据源
1 List<String> list = new ArrayList<String>(); 2 list.add("苹果"); 5 list.add("香蕉"); 7 list.add("橘子"); 9 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);
系统提供的样式如下
l simple_spinner_dropdown_item(列表-间距较高比较好看)
l simple_spinner_item(列表-间距紧凑不好看)
l simple_list_item_checked(复选框-选中的有绿沟)
l simple_list_item_single_choice (单选按钮)
6.向控件Spinner添加适配器
1 Spinner sp=(Spinner) findViewById(R.id.spinner1); 2 sp.setAdapter(adapter);
释义
1. setAdapter(SpinnerAdapter adapter) ,从类的继承关系上看,ArrayAdapter是SpinnerAdapter接口的间接实现类
7.实现选择项事件(使用匿名类实现接口)
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 });
8.后台整体代码如下
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/lxcao/p/4299067.html