Spinner中的选项数据通过ArrayAdapter设置,其中的数据来源可以来自程序中数组,也可以来自xml中自定义数据。
?
1,通过ArrayList获得选项数据如下:
?
Spinner spinner=null; Spinner spinner2=null; private static final String[] countries={"China","Russia","Germany","America","Belarus","Japan"}; List allcountries=null; ArrayAdapter<String> adapter; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); textView=(TextView) findViewById(R.id.text); spinner=(Spinner) findViewById(R.id.spinner); allcountries=new ArrayList<String>(); for(int i=0;i<countries.length;i++){ allcountries.add(countries[i]); } adapter=new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item,allcountries); adapter.setDropDownViewResource(R.layout.myspinner_dropdown); spinner.setAdapter(adapter);
其中使用了自定义选项样式,?R.layout.myspinner_dropdown:
myspinner_dropdown.xml:
<?xml version="1.0" encoding="utf-8"?><TextView xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/text1" android:layout_width="wrap_content" android:layout_height="24sp" android:singleLine="true" style="?android:attr/spinnerDropDownItemStyle"></TextView>
?
2,通过xml中定义获得数据如下:
?
spinner2=(Spinner) findViewById(R.id.spinner2); ArrayAdapter<CharSequence> adapter2=ArrayAdapter.createFromResource(this, R.array.countries, android.R.layout.simple_spinner_item); adapter2.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); spinner2.setAdapter(adapter2);
?在res/values中增加array.xml:
<?xml version="1.0" encoding="utf-8"?><resources><string-array name="countries"> <item>China2</item> <item>USA2</item> <item>Japan2</item> <item>Germany2</item> <item>Belarus2</item> <item>Russia2</item></string-array></resources>
?选择和点击Spinner选项触发事件,其中选择事件如下:
spinner2.setOnItemClickListener(new Spinner.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) { // TODO Auto-generated method stub textView.setText("选的是:"+countries[arg2]); } });
?