参考:http://www.dedeyun.com/it/m/98498.html
https://blog.csdn.net/myxiaoq/article/details/25869693
1.key、value类,需要重写toString()方法,返回text就是Spinner要显示的key
https://blog.csdn.net/myxiaoq/article/details/25869693
1.key、value类,需要重写toString()方法,返回text就是Spinner要显示的key
package com.jay.common; public class SpinnerData { private String value = ""; private String text = ""; public SpinnerData() { value = ""; text = ""; } public SpinnerData(String _value, String _text) { value = _value; text = _text; } @Override public String toString() { return text; } public String getValue() { return value; } public String getText() { return text; } }
2.设置适配器,默认选中项:spinner.setSelection(1);要放到最后一行。
Spinner spinner = (Spinner) findViewById(R.id.cbo1); List<SpinnerData> lst = new ArrayList<SpinnerData>(); for (int i = 0; i < 3; i++) { SpinnerData c = new SpinnerData("value"+i, "text" + i); lst.add(c); } ArrayAdapter<SpinnerData> Adapter = new ArrayAdapter<SpinnerData>(this,android.R.layout.simple_spinner_item, lst); Adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); spinner.setAdapter(Adapter);
3.获取当前选中项:((SpinnerData)spinner.getSelectedItem()).getValue();
4.设置选中事件
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { TextView view1 = (TextView) view; String k = view1.getText().toString(); String v = lst.get(position).getValue(); Toast.makeText(MainActivity.this, "text:" + k + ",\nvalue:" + v, Toast.LENGTH_SHORT).show(); } @Override public void onNothingSelected(AdapterView<?> parent) { } });
5.可替换自定义列表、选中样式
item_select.xml
<?xml version="1.0" encoding="utf-8"?> <TextView xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="45dp" android:background="@android:color/holo_blue_dark" android:textSize="14sp" android:textColor="@android:color/holo_red_light" android:gravity="center" />
item_dropdown.xml
<?xml version="1.0" encoding="utf-8"?> <TextView xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="45dp" android:textColor="@android:color/black" android:textSize="14sp" android:gravity="center"/>