spinner 从数据库读取数据并实现二级联动。
这里主要实现了。省份和城市的二级关联。选择省份。二级对应的就是省份所有的城市
下面看代码;
1.activity
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.test_layout);
this.mContext = this;
Map<Integer,List> data = ProvinceDB.getProvince();//得到数据库数据
provinceList = data.get(1);
provinceData = data.get(0);
ArrayAdapter provinceAdapter = new ArrayAdapter(mContext,android.R.layout.simple_spinner_item,provinceList);
provinceAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); // 样式
spProvince.setAdapter(provinceAdapter);
spProvince.setOnItemSelectedListener(itemSelectedListener);
}
// 选择省份 联动 对应城市
private OnItemSelectedListener itemSelectedListener = new OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view,
int position, long id) {
Spinner spProvince = (Spinner) parent;
String selProvince = (String) spProvince.getItemAtPosition(position);
ArrayAdapter cityAdapter = null;
Map<String,Integer> data = (Map)provinceData.get(position);//根据所选择的得到对应的省份id 然后得到城市
int pid = data.get(selProvince);//得到省份的id
&