以前做过,数据是在本地xml里面取的:上面是省市区的xml数据网盘地址。 如果要做成从服务器取,那么就一次性取下来,然后还是一样的流程。如果你想选择省再去取对应的市,那么就要传省的id去获取对应的市,这时候就要有等待框,可能用户体验差一点。
成都创新互联是一家以网站建设公司、网页设计、品牌设计、软件运维、成都网站营销、小程序App开发等移动开发为一体互联网公司。已累计为成都阳光房等众行业中小客户提供优质的互联网建站和软件开发服务。
public class Area {
private String province;
private String city;
//省略属性区和get set方法
public boolean isSame(Area area){
if(!area.getProvince().equals(province)){
return false;
}
if(!area.getCity().equals(province)){
return false;
}
//省略 区
return true;//相同
}
}
Androidspinner实现省市二级联动,需要自定义adpter,将数据源绑定到adpter,当点击省时,触发自定义响应事件,改变市,示例如下:
public class MainActivity extends Activity {
private TextView textView ;
private Spinner province;
private Spinner city;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//String[] provinces = new String[]{"-省份-","河北省","山西省","北京"};
textView = (TextView)this.findViewById(R.id.textView);
province = (Spinner)this.findViewById(R.id.province);
city = (Spinner)this.findViewById(R.id.city);
//(处理省的显示)
//将可选内容与ArrayAdapter的连接(从资源数组文件中获取数据)
ArrayAdapterCharSequence adapter =
ArrayAdapter.createFromResource(this, R.array.province, android.R.layout.simple_spinner_item);
//new ArrayAdapterString(this,android.R.layout.simple_spinner_item, provinces);
//设置下拉列表的风格
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
//将数据绑定到Spinner视图上
province.setAdapter(adapter);
//添加条目被选中监听器
province.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView? parent, View view,int position, long id) {
//parent既是province对象
Spinner spinner = (Spinner)parent;
String pro = (String)spinner.getItemAtPosition(position);
//(处理省的市的显示)
//将默认值与ArrayAdapter连接(从资源数组文件中获取数据)
ArrayAdapterCharSequence cityAdapter = ArrayAdapter.createFromResource
(MainActivity.this, R.array.citydefault, android.R.layout.simple_spinner_item);
//new ArrayAdapterCharSequence
// (MainActivity.this,android.R.layout.simple_spinner_item, cities);
//获取所在省含有哪些市(从资源数组文件中获取数据)
if(pro.equals("河北省")){
cityAdapter = ArrayAdapter.createFromResource
(MainActivity.this, R.array.hb, android.R.layout.simple_spinner_item);
}else if(pro.equals("北京市")){
cityAdapter = ArrayAdapter.createFromResource
(MainActivity.this, R.array.bj, android.R.layout.simple_spinner_item);
}else if(pro.equals("山西省")){
cityAdapter = ArrayAdapter.createFromResource
(MainActivity.this, R.array.shx, android.R.layout.simple_spinner_item);
}
//绑定数据到Spinner(City)上
city.setAdapter(cityAdapter);
}
@Override
public void onNothingSelected(AdapterView? parent) {
}
});
}
}