转载自:http://www.cnblogs.com/xinsheng/archive/2011/04/26/2029185.html
下拉菜单Spinner用法,效果图:
布局xml代码:
<Spinner android:id="@+id/sp1" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="下拉菜单" android:drawSelectorOnTop="true" android:prompt="@string/planet_prompt"/>?上面的prompt属性就是点击后跳出的选择框的标题栏上的文字,本来想直接打上字符串,但是提示出错,而把字符串放进string.xml就没问题,不知什么原因。
string.xml:
<string name="planet_prompt" >Choose a planet</string>
?最后是程序代码:
package com.pocketdigi; import java.util.List; import android.app.Activity;import android.os.Bundle;import android.view.View;import android.widget.AdapterView;import android.widget.ArrayAdapter;import android.widget.Spinner;import android.widget.Toast;import android.widget.AdapterView.OnItemSelectedListener; public class main extends Activity { /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); SpDemo(); } Spinner sp1; ArrayAdapter<String> adapter; List<String> allnum; private static String[] arr={"1","2","3"};//定义一组选项 private static String[] Value={"我是1","我是2","我是3"};//定义选中后得到的值 private void SpDemo() { //下面开始插入数据 sp1=(Spinner)findViewById(R.id.sp1); adapter=new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item,arr); //将可选内容与ArrayAdapter连接 adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); //设置下拉列表的风格 sp1.setAdapter(adapter); //将adapter添加到Spinner中 //插入数据结束 //下面开始获取选中的值 sp1.setSelection(2); sp1.setOnItemSelectedListener(new OnItemSelectedListener(){ @Override public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3) { // TODO Auto-generated method stub Toast.makeText(main.this, Value[arg2],10).show(); } @Override public void onNothingSelected(AdapterView<?> arg0) { // TODO Auto-generated method stub Toast.makeText(main.this, "没选中",10).show(); } }); }}
上面代码中,插入数据那段,还可以用以下方法:
方法一,直接在程序中add
sp1=(Spinner)findViewById(R.id.sp1);adapter=new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item);adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);adapter.add("1");adapter.add("2");adapter.add("3");sp1.setAdapter(adapter);
??方法二,把数据放入xml文件中
在res\layout目录下建立新的XML文件,文件名为Spinner.xml,内容如下:
<?xml version="1.0" encoding="utf-8"?><resources> <string-array name="num"> <item>1</item> <item>2</item> <item>3</item> </string-array></resources>
?主程序加入数据那段代码改为下面的代码:
sp1=(Spinner)findViewById(R.id.sp1);ArrayAdapter<CharSequence> Ad=ArrayAdapter.createFromResource(this, R.array.num,android.R.layout.simple_spinner_item);Ad.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);sp1.setAdapter(Ad);?注意:这段用的是ArrayAdapter<CharSequence>,上面两种用的是ArrayAdapter<String>,所以重新定义ArrayAdapter