一分钟掌握Android spinner下拉框
Android 自带的spinner下拉框控件是一个不错的系统控件。主要有两种实现方式:
1.静态的spinner
在res\values中加入一个city资源数组文件
2 <resources> 3 4 <string-array name="city"> 5 <item>北京</item> 6 <item>上海</item> 7 <item>广州</item> 8 <item>厦门</item> 9 </string-array> 10 11 </resources>设置代码
Spinner sp = (Spinner) findViewById(R.id.spinner1); sp.setOnItemSelectedListener(new Spinner.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3) { Log.e("arg2",arg2);//id } @Override public void onNothingSelected(AdapterView<?> arg0) { } }); ArrayAdapter adapter =ArrayAdapter.createFromResource(this,R.array.city, android.R.layout.simple_spinner_item); sp.setAdapter(adapter); sp.setSelection(0);//默认选择第一项
2.动态的spinner
ArrayList<String> al=new ArrayList<String>(); al.add("北京"); al.add("上海"); Spinner sp = (Spinner)findViewById(R.id.spinner1); sp.setOnItemSelectedListener(new Spinner.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3) { Log.e("arg2",arg2);//id } @Override public void onNothingSelected(AdapterView<?> arg0) { } }); ArrayAdapter<String> adapter =new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item,al);//要加图片可自己定义适配器 sp.setAdapter(adapter); sp.setSelection(1);//默认选择第二项注:setAdapter()方法加入的时机必须在容器集合获取到相关数据后,否则spinner内容无法显示;
setSelection()方法必须最后运行,否则无法选择指定项;
资源文件转数组:getResources().getStringArray(R.array.x);